Search code examples
javascriptclassparameter-passingdestructuring

How can I use default parameters when no value are passed in creating a new object?


I'm trying to pass parameters to a new class constructor and have default parameters calculated if no arguments are passed, whilst still having the option of passing any parameter by it's argument name.

class thing{
 constructor({a = 0, b = 0}) { 
  if(a == 0){this.a= func();}
  else {this.a = a;}
  if(b == 0){this.b= func();
  else {this.b = b;}
}
var defaultThing = new thing(); // returns Cannot destructure property `a` of 'undefined' or 'null'. 
var parametersThing = new thing({b:20}); // returns {a = 0, b = 20}

The problem is that when no parameters are passed the error Cannot destructure property `a` of 'undefined' or 'null'. is returned.

How can I use default parameters and still be able to use no parameters without encountering this error?


Solution

  • In your constructor signature, you've supplied destructuring defaults for when the properties don't exist on the parameter received, but no default parameter. To do that, you add a default parameter:

    //                         vvvv−−− default parameter value
    constructor({a = 0, b = 0} = {}) {
    //             ^^^−−−−^^^−−−−−−−−− destructuring defaults
        // ...
    

    If you call that with no arguments, the default parameter value ({}) kicks in, and then the destructuring defaults kick in because that {} object doesn't have a or b.