Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,253 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
231,248 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 91,253 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!