Skip to content

JavaScript class constructor default values | Example code

  • by

You can set the JavaScript class constructor default values in the parameters. if there is no parameter passing through the constructor, it is assigned a default value as it was pre-set.

class User {
  constructor(fullName = "fooName", lastName, canAccess = false) {
    this.fullName = fullName;
    this.lastName = lastName;
    this.canAccess = canAccess;
  }
}

JavaScript class constructor default values

Simple HTML example code of class default parameters in JavaScript.

<!DOCTYPE html>
<html>
<body>
  <script>
    class myClass {
      constructor({a = 'default a value', b = 'default b value', c = 'default c value'} = {a:'default option a', b:'default option b', c:'default option c'}) {
        this.a = a;
        this.b = b;
        this.c = c;
      }
    }
    
    var v = new myClass({a:'a value', b: 'b value'});
    console.log(v);

    var w = new myClass();
    console.log(w);

  </script>
</body>
</html> 

Output:

JavaScript class constructor default values

You could either set a default value for options, i.e {}.

class User {
    constructor(options = {}) {
        this.name = options.name || "Joe";
        this.age = options.age || 47;
    }
}

or first, check for options to be truthful and then access the value.

class User {
    constructor(options) {
        this.name = options && options.name || "Joe";
        this.age = options && options.age || 47;
    }
}

Do comment if you have any doubts or suggestions on this JS constructor topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *