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 trialMARIA Quadri
2,572 PointsI'm stuck on this code.
I've defined the object literal but I don't know what I'm doing wrong since i keep getting an error.
const myString = {
string: "Programming with Treehouse is fun!",
words: countWords() {
return string.length;
}
};
4 Answers
Cooper Runstein
11,850 PointsBeyond just needing to use split, you need to correctly get the string value using the this keyword.
const myString = {
string: "Programming with Treehouse is fun!",
countWords: function(){
words = this.string.split(' ')
return words.length
}
}
KRIS NIKOLAISEN
54,971 PointsIn this challenge you are counting words in the string not characters.
MARIA Quadri
2,572 Pointsoh good point, but how do I count the words?
Cooper Runstein
11,850 PointsIn a sentence, a "word" is a set of characters separated by a space, so you need to find a way to break the string up wherever you see a space. I'd use the split method (https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/String/split). You can input the character you want to split on as a string containing a space, and then count how many items there are.
The other way to do this is count how many spaces there are. You could use regex for this, or you could filter out everything that isn't a space. I prefer the split method because you could further analyze the words to make sure they truly are words, but for this challenge, either way works.
MARIA Quadri
2,572 Pointswhy do we have to add the word "this"?
Cooper Runstein
11,850 Pointshttps://www.w3schools.com/js/js_this.asp https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this Read the links above for more info, but in short, this gives you access to the context of the object that owns the function you're creating.
var person = { //this object creates a new "wrapper" over the internal properties/methods
name: 'Maria', //I create a property that belongs to the person object
returnName = function(){ //I create a function that belongs to the person object
return this.name; // I use this to access the property name that belongs to the object that owns this function
}
}
MARIA Quadri
2,572 PointsThanks for the responses. I get it ! :D