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 trialTSENG FUCHUN
4,287 PointsI 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
Treehouse TeacherHi 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
Hope this helps!
TSENG FUCHUN
4,287 PointsTSENG FUCHUN
4,287 PointsJennifer 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
Treehouse TeacherJennifer Nordell
Treehouse TeacherTSENG 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 thesplit
method on thestring
property ofmyString
. Thestring
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 methodcountWords
it would have printed out a numberTSENG FUCHUN
4,287 PointsTSENG FUCHUN
4,287 PointsJennifer Nordell Hello Again! I just figure out, really appreciate! Thank you!