JavaScript Introducing ES2015 Classes Structure of Class

jlampstack
jlampstack
17,748 Points

Why pass {} = {} to constuctor?

What is the importance of passing the second object?

Why write....

class Student {
    constructor( {name, city, interestLevel = 5} = {} ) {
        this.name = name;
        this.city = city;
        this.interestLevel = interestLevel;
    }
}


let john = new Student({ name: 'John', city: 'Portland', interestLevel: 5});


console.log(john);

When we can write....

class Student {
    constructor( {name, city, interestLevel = 5} ) {   // This is the only line that is different
        this.name = name;
        this.city = city;
        this.interestLevel = interestLevel;
    }
}


let john = new Student({ name: 'John', city: 'Portland', interestLevel: 5});


console.log(john);

3 Answers

Steven Parker
Steven Parker
171,227 Points

That first set of braces define the kind of object that the constructor will take. If you have that by itself, then every instantiation must supply an object.

The "= {}" part afterwards establishes a default, so if the constructor is called without an argument, an empty object will be supplied. This makes the argument optional instead of mandatory when you create an instance.

Peter Retvari
Peter Retvari
Full Stack JavaScript Techdegree Student 8,391 Points

Hi folks, how about this one? I don't understand why we use curly braces:

class Student {
  constructor(name, age, interestLevel = 5) {
    this.name = name;
    this.age = age;
    this.interestLevel = interestLevel;
  }
}

let joey = new Student('Joey', 25);
let chandler = new Student('Chandler', 26);

console.log(joey);
console.log(chandler);
Steven Parker
Steven Parker
171,227 Points

You'd have the same issue as Jay then, you could only create an instance if you supply a name and age. The purpose of passing the arguments through an object, and having a default object, is that it allows you to create an instance with no arguments if you want:

let someone = new Student();