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 Staff

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 Staff

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!