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 Adding a Method Solution

I just don't know why need to return the length of the array

This is the correct answer below:

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

console.log(myString.string.split(" "));

But these 2 lines, I can't figure out why.

const wordArray = this.string.split(' ');
return wordArray.length;

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, TSENG FUCHUN ! The biggest clue here is in the name of the method, which is countWords. That's literally what it does. It counts the words in a string. The split(" ") divides the string at the spaces, so the string "I love Treehouse", would result in an array with ["I", "love", "Treehouse"]. The length of that array is 3. Three words in the string and that's exactly what we return :smiley:

Hope this helps! :sparkles:

Jennifer Nordell Thank you for answering me, that's really helpful! Now I know the return value will be 5, and I still confuse about this: I can't figure out why this line will be related to the function "countWords"

console.log(myString.string.split(" "));

Because this line don't mention anything about the function.

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

TSENG FUCHUN Hi again! That line doesn't have anything to do with the countWords method. It is showing the result of what happens if you use the split method on the string property of myString. The string property is just there holding a string and if you ran the split on it directly, what's returned is an array of the individual words. You can see the results at 2:25 of the video linked here. If it were running the method countWords it would have printed out a number :smiley:

Jennifer Nordell Hello Again! I just figure out, really appreciate! Thank you!