JavaScript Practice Object Basics in JavaScript Practicing Object Basics Adding a Method Solution

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 87,013 Points

Is this "wrong"?

First things first, I know there's always more than one way to solve a problem.

But when I did this code challenge I used the following syntax to create my method,

countWords: function countWords(words) { 
 //code

  }

So that's the same of the method and then a named function of the same name as the key.

But Ashley used an anonymous function.

countWords: function() {
  //code
}

Can't help but think my way bad practice?

1 Answer

Steven Parker
Steven Parker
203,722 Points

Perhaps not exactly "bad practice", but unnecessary. Your syntax explicitly names the function, but when an anonymous function is assigned it implicitly acquires the name of the variable it is assigned to. So it's more common (and more compact) to use anonymous syntax in function expressions.

The big difference between these two is that your function takes an argument ("words") and the other one does not.

Good seeing you online again, and happy coding!

Jonathan Grieve
Jonathan Grieve
Treehouse Moderator 87,013 Points

Yes, I've been trying some experiments and the parameter was a hangover from that. :)

Thanks. I'm really trying to get my head around OOP JavaScript before moving onto the example course. I'll try to avoid my syntax in future!