JavaScript Practice Object Basics in JavaScript Practicing Object Basics Practice Adding a Method to an Object Literal

MARIA Quadri
MARIA Quadri
2,572 Points

I'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.

mystring.js
const myString = {
    string: "Programming with Treehouse is fun!",
  words: countWords() {
   return string.length;
}
};

4 Answers

Cooper Runstein
Cooper Runstein
11,822 Points

Beyond 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
        }
}

In this challenge you are counting words in the string not characters.

MARIA Quadri
MARIA Quadri
2,572 Points

oh good point, but how do I count the words?

Cooper Runstein
Cooper Runstein
11,822 Points

In 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
MARIA Quadri
2,572 Points

why do we have to add the word "this"?

Cooper Runstein
Cooper Runstein
11,822 Points

https://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
MARIA Quadri
2,572 Points

Thanks for the responses. I get it ! :D