Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects Player Properties Solution

Best practice for declaring properties within a class?

In the video, Ashley declares the empty array tokens in the constructor of the Player class.

Testing with the console in the browser, I can see that declaring it in the body of the class is also accepted: it returns a value when an object is instantiated.

I wonder what is considered best practice for declaring properties: declaring in the constructor method like this:

class Player {
   this.tokens = [];

... or in the class body, like this:

class Player {
  tokens = [];

Obviously we wouldn't be able to pass in a value to the property upon instantiation unless it were declared in the constructor, but if we were planning to use a setter method to provide a value after instantiation instead then is there any benefit to declaring the empty property in the constructor method?

1 Answer

Steven Parker
Steven Parker
217,469 Points

Like many things in programming, it's programmer's choice. But the 2nd form is a bit more concise, and it can be even more so if you leave off the definition of the empty constructor completely.

I might prefer the first form if there were to be other instance variables initiated in the constructor, just to keep them all together.

That's a very good answer; I agree with your logic.

Ah so we don't technically need a constructor? Interesting.

Quite dynamic then, Javascript..