JavaScript Practice Object Basics in JavaScript Practicing Object Basics Practice Adding a Property on the Fly

Sam Weeks
Sam Weeks
Front End Web Development Techdegree Student 16,699 Points

How is this code returning the incorrect value for the code challenge?

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


var numWords = myString.countWords();

myString.characters = function () {
  return this.string.length
}; 

1 Answer

Steven Parker
Steven Parker
203,716 Points

I see two issues:

  • the instructions ask just for a property, not a new method/function
  • you cannot use "this" outside of the object, reference the object by name instead
Sam Weeks
Sam Weeks
Front End Web Development Techdegree Student 16,699 Points

I see what your saying with the first issue however when i ran this via the console it returned the same value i.e myString.character = myString.string.length: returns 34 and the code I used above when logging myString.character() returns 34

Steven Parker
Steven Parker
203,716 Points

The challenge is looking for you to create the property containing a value as the instructions ask. The function may generate the same value, but type of the property will be different.

For best results with the challenges, always do what the instructions ask for!