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;
    }
}

Here’s how you can define default values in a class constructor:

class MyClass {
  constructor(param1 = defaultValue1, param2 = defaultValue2) {
    this.param1 = param1;
    this.param2 = param2;
  }
}

const instance1 = new MyClass(); // Both parameters use their default values.
console.log(instance1.param1); // Output: defaultValue1
console.log(instance1.param2); // Output: defaultValue2

const instance2 = new MyClass("customValue", "anotherValue");
console.log(instance2.param1); // Output: customValue
console.log(instance2.param2); // Output: anotherValue

In the example above, the MyClass constructor has two parameters, param1 and param2, both of which have default values. When you create an instance of MyClass, you can provide values for these parameters, and if you don’t provide values, the default values will be used.

Note: default values can be any valid JavaScript expression, so you can use more complex logic to compute default values if needed.

This feature was introduced in ECMAScript 6 (ES6), so make sure your environment supports ES6 features to use default values in class constructors.

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 *