Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Constructing an object without passing at least empty curly brackets produces "(destructured parameter) is undefined" type error

I’m trying to write a class with optional named arguments.

class MyClass {
      constructor({a=2, b=4, c=3}){
          console.log(b);
      }
    }

If I create the object like this

let obj = new MyClass({});

then all is good.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, if I create the object like this

let obj = new MyClass();

I get an error. Is it possible to make it accept empty parentheses?

>Solution :

Have the whole argument also default to the empty object (in addition to the destructured properties defaulting to particular values).

class MyClass {
  constructor({ a=2, b=4, c=3 } = {}){
      console.log(b);
  }
}
let obj = new MyClass();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading