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 Object-Oriented JavaScript: Challenge Building Constructor Methods and Generating Objects Player Properties Solution

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

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 {
  constructor(){
   this.tokens = [];
  }
}

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

class Player {
  constructor(){}
  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
230,274 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.

Alex Hort-Francis
Alex Hort-Francis
17,074 Points

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..