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

Alasdair Marchant
Alasdair Marchant
4,592 Points

how do I count the number of words?

I can't work it out and google doesn't help

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

1 Answer

Hi

you're very close, you just need to add a split() method. like this

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