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
PoJung Chen
5,856 PointsWhy need to pass an empty object in parameter of class constructor ?
I know we can use object destructuring in ES6. However, in the course, it set the parameter of constructor such as
class Person {
constructor ({firstname, lastname, country = 'Taiwan'} = {}) {
...
}
}
in the parameter {firstname, lastname, country = 'Taiwan'} = {}
why I need to pass it to an empty object?
I found that I could write
constructor ({firstname, lastname, country = 'Taiwan'} ) {
...
}
and it will return the same result.
So I am wondering why teacher always set the object to an empty object?
1 Answer
Steven Parker
243,318 PointsGiving the constructor an empty object default lets you to instantiate with no arguments.
With the default empty object as in your first example, you can then create a new instance without providing any arguments, like this
let Joe = new Person();
But if you have no default, as in your second example, that code would cause an error. You would then be required to provide an argument, even an empty one, for each instance you create.
PoJung Chen
5,856 PointsPoJung Chen
5,856 PointsGot it! Thanks a lot!