Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

jamesjones21
jamesjones21
9,260 Points

Arrow functions within an object literal in JavaScript

Hi,

I have a question in relation to using arrow functions within an object literal.

The below code works as expected with the anonymous function being used

const ernie = {
    //this is a key value pair where the animal property is representing the value of dog.
    animal: 'dog',
    age: 1,
    breed: 'pug',
    sentence: 'this is a test of words that we count',
    //this is a method
    bark: function () {
        console.log('woof');
    },

    countWords: function() {
        //to count words within a string we have to split the word by a space.
        //cannot use arrow functions in a object literal
        const splitWords = this.sentence.split(' ');
        return splitWords.length;
    }


}

console.log(ernie);

But the following code just gives an error when arrow functions are used to define a method within the object literal:

const ernie = {
    //this is a key value pair where the animal property is representing the value of dog.
    animal: 'dog',
    age: 1,
    breed: 'pug',
    sentence: 'this is a test of words that we count',
    //this is a method
    bark: () => {
        console.log('woof');
    },

    countWords: function() {
        //to count words within a string we have to split the word by a space.
        //cannot use arrow functions in a object literal
        const splitWords = this.sentence.split(' ');
        return splitWords.length;
    }


}
console.log(ernie);

'''

Could someone please shed some light on this matter? :)
jamesjones21
jamesjones21
9,260 Points

Actually it does work -_- must have been me as it was late at night so thanks for the reply, just needed some extra sleep doh !

1 Answer

Rich Donnellan
MOD
Rich Donnellan
Treehouse Moderator 27,696 Points

In your second example, console.log(ernie) isn't outside of the ernie object literal.

It can't "log itself from within itself".

jamesjones21
jamesjones21
9,260 Points

I understand that, but it kick's out an error whenever you try to use an arrow function to declare a function. Which is odd. The second console.log is a typo apologies

Rich Donnellan
Rich Donnellan
Treehouse Moderator 27,696 Points

Where are you trying to run this code? It works when I paste into Chrome DevTools.