0

can someone explain me what the ={} expression in the code below is there for?

class Dragon {

    constructor({ birthdate, nickname, traits } = {}) {
        this.birthdate = birthdate || DEFAULT_PROPERTIES.birthdate;
        this.nickname = nickname || DEFAULT_PROPERTIES.nickname;
        this.traits = traits || DEFAULT_PROPERTIES.randomTraits;


    }
}

Masenko 22
  • 35
  • 1
  • 1
  • 5

2 Answers2

1

Default value for the paremeter. The constructor takes an object as its only argument, if you call the function without any arguments, an empty object (i.e. {}) will be given as the parameter

Note that the function only accepts one parameter, though it may look like 3 because of the object destructuring syntax

Jason
  • 632
  • 1
  • 5
  • 17
0

Look at the code below:

function sayHello(name){
  const nameToPrint = name || "Unknown"
  console.log('Hello' + nameToPrint)
}

sayHello('Tylor')
// Hello Tylor

sayHello()
//Hello Unknown

This function is a totally valid function. The value of nameToPrint will either be a name passed in, or Unknown, in case the argument name is not provided.

Now let's change this a little bit:

 function sayHello({name}){
      const nameToPrint = name || "Unknown"
      console.log('Hello' + nameToPrint)
  }

    sayHello('Tylor')
    // Hello Tylor

    sayHello()
    //Cannot destructure property 'name' of 'undefined' as it is undefined.

The function, now, will throw an error if the argument name is not provided. This is due to the fact that it will try to destructor from an object which is not provided(AKA from undefined), which will ultimately result in an error. by adding ={} we are adding a default value for the object. So now, if the argument(s) are not provided, they will be undefined(a falsy value); and, the values for those arguments, will be the fallback ones(the values after ||).

Going back to our example:

function sayHello({name} = {}){

  const nameToPrint = name || "Unknown"
  console.log('Hello' + nameToPrint)
}

sayHello('Tylor')
// Hello Tylor

sayHello()
//It will try to extract the property name from object {}
// The value of name will be undefined, so the value of nameToPrint will be "Unknown"
//Hello Unknown

To conclude, trying to access a property of undefined, will trigger an error, but trying to access a property of an empty object, will only cause the value to be undefined. See this for more info

Parsa Safavi
  • 218
  • 2
  • 10