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;


    }
}

2
  • 1
    {} is default value for the argument (an Object) Commented Sep 11, 2020 at 21:20
  • possible duplicate of stackoverflow.com/questions/35526463/… Commented Sep 11, 2020 at 21:51

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.