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

Stan Dav
Stan Dav
3,213 Points

Hello, why my code is returning error Bummer: Cannot read property 'split' of undefined

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

also why I'm doing this attribute method when we can just say console.log(myString.string.split(' '));

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

1 Answer

Daniel Turato
seal-mask
PLUS
.a{fill-rule:evenodd;}techdegree seal-36
Daniel Turato
Java Web Development Techdegree Graduate 30,119 Points

Your code looks good but maybe its not recognising the function declaration syntax. I did this and it worked for me:

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