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 Practice Object Basics in JavaScript Practicing Object Basics Practice Adding a Method to an Object Literal

Adding a method to an object literal - error unexpected identifier

I'm stuck with the challange task, where I have to add a method to an object literal. I'm getting an error "Unexpected identifier" and I don't know what I have to do, please help.

mystring.js
const myString = {
    string: "Programming with Treehouse is fun!"
  countWords: function(){
    const wordArray = this.string.split(' ');
    return wordArray.length;
  }
}

Add a method to the object literal called countWords(). countWords() should return the number of individual words in the string property.

Blake Larson
Blake Larson
13,014 Points

Add a comma after the string: "Programming with Treehouse is fun!"

1 Answer

hello, can someone please explain how this.string.split gets put in the answer. and also where did they fetch wordarray from?? it's fun to learn all this but then the exercises are like 100 times more difficult than what we learn... man i been on this for 3 hours trying to figure it out myself and google...

Blake Larson
Blake Larson
13,014 Points

wordArray is a variable that stores the return value of the split built in String method which is returned as an array.

When you use `string.split(' ') <-- Splits the string into an array at all the spaces.

When you use `string.split('') <-- Splits the string into an array of all chars in the string.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split <-- split docs.

const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[3]);
// expected output: "fox"

const chars = str.split('');
console.log(chars[8]);
// expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

So the countWords() function returns the how many words are in the this object.string.