Nighel
Nighel

Reputation: 161

Setting default values for properties in Javascript

How can I set default values for the properties p1,p2,p3 and p4` of a class:

class O extends AnotherClass {

    constructor(p1,p2,p3,p4) {
    super(); \\ for the this-reference
    if (p1) this.p1 = p1;
    if (p2) this.p2 = p2;
    if (p3) this.p3 = p3;
    if (p4) this.p3 = p4;

    }

do I have to write one by one

O.prototype.p1 = "default1"
O.prototype.p2 = "default2"
O.prototype.p3 = "default3"
O.prototype.p4 = "default4"

or is there a more elegant way, like

O.prototype = {p1: "default1", p2 : "default1", p3 : "default3", p4 : "default4"}

but the latter does not seem to work...

Upvotes: 1

Views: 2094

Answers (3)

Davoud Ramezani
Davoud Ramezani

Reputation: 1

  constructor(p1, p2, p3, p4) {
    super();
    if (p1) this.p1 = p1 === undefined ? "p1Default" : p1;
    if (p2) this.p2 = p2 === undefined ? "p2Default" : p2;
    if (p3) this.p3 = p3 === undefined ? "p3Default" : p3;
    if (p4) this.p3 = p4 === undefined ? "p4Default" : p4;
  }

Upvotes: 0

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64933

In addition to plain ES2015+ default parameter values as @Fried_Chicken has already answered, there's still an alternate approach.

Why don't you accept arguments as an object and then, you use ES2015+ destructuring capabilities? This is a great choice as you can provide the whole arguments in any order, or even provide just one or some of them.

Also, you won't need to provide null/undefined to some given parameters:

doStuff(1, null, null, 2); 

See the following runnable code snippet and play with it. The same solution can be applied in your scenario as destructuring can be used on class constructors.

function doStuff({ arg0 = null, arg1 = null } = {}) {
  if (arg0 !== null) {
      console.log(arg0);
  } else {
      console.log("not provided");
  }
}

doStuff();
doStuff({ arg0: "hello world" });

Upvotes: 1

Simon Mo
Simon Mo

Reputation: 772

You can set default properties in es6 when you declare params in your constructor like this constructor(p1 = 'Default Variable',p2 = 'Default Variable',p3 = 'Default Variable',p4 = 'Default Variable')

Upvotes: 5

Related Questions