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

Richard Preske
PLUS
Richard Preske
Courses Plus Student 4,353 Points

countWords issue

I know this function doesn't return anything but shouldn't we be able to use substring method to count the words? Let me know a hint if there is a different way or way to use substring. Thanks.

mystring.js
let count;
const myString = {
    string: "Programming with Treehouse is fun!",
  countWords: function() {
      if (this.string.substring(0, 10) === 'Programming') {
        count = 1;
      }
      if (this.string.substring(12, 15) === 'with') {
        count += 1;
      }
      if (this.string.substring(17, 25) === 'Treehouse') {
        count += 1; 
      }
      if (this.string.substring(27, 28) === 'is') {
        count += 1; 
      }
      if (this.string.substring(30, 32) === 'fun') {
        count += 1;
      }
      return (count); 
}
}

1 Answer

Steven Parker
Steven Parker
203,716 Points

The "count" isn't initialized in the method, and the ending indexes for the "substring" calls should be the index of the first character not included. For example, "myString.substring(12, 15)" would return "wit".

But this isn't quite what was being asked for. A proper solution should return a correct count even if the string were replaced with something completely different. Try creating a method that would handle that situation also.