Search code examples
javascriptclassobjectargumentsdefault

Create default in constructor function if no argument is passed - javascript


I have the following:

class example {
   constructor (arg) {
      this.value = arg.value
   }
   print () {
      console.log(this.value);
   }
}

var new_example = new example  ({
   value: 12,
})

new_example.print();

How do I set a default value where say value = 10, such that, if no argument was given, it would print 10. I.e.:

var newer_example = new example ({
})

I've tried things like:

class example {
   constructor (arg) {
      this.value = (arg.value || 10)
   }
   print () {
      console.log(this.value);
   }
}

And:

class example {
   constructor (arg) {
      this.value = ("undefined" != arg.value || 10)
   }
   print () {
      console.log(this.value);
   }
}

But can't find anything that works.


Solution

  • You can use defaults for the arguments, and you can use destructuring with further defaults for the object properties to support both new example() and new example({}):

    class example {
       constructor ({ value = 10 } = {}) {
          this.value = value
          // Note: You could also use Object.assign(this, { value }) which
          // can become useful once you have more values in your object
       }
       print () {
          console.log(this.value);
       }
    }