2

In looking at an article on javascript classes, the author uses this syntax:

class GuitarAmp {
    constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
     Object.assign(this, {
      cabinet, distortion, volume
     });
   }
}

What is the purpose of the = {} bit in the constructor parameter listing? Aren't we setting default parameters for cabinet, distortion and volume?

4
  • 1
    It's setting a default if you don't supply any arguments i.e object Commented Apr 11, 2018 at 3:28
  • you should google or MDN ,shouldn't ask here before searching Commented Apr 11, 2018 at 3:29
  • @xianshenglu May I ask what you'd recommend I search on for a question like this? 'What does = {} mean in a constructor?' wouldn't get many valid results. Commented Apr 11, 2018 at 3:37
  • 1
    I believe it's saying that if an object is passed, those are the default values (for cabinet, distortion, volume) if those individual properties are not declared within the object, and if no parameter is supplied to the function, the default is the empty object {}. Commented Apr 11, 2018 at 3:40

1 Answer 1

4

It lets you call GuitarAmp without any parameters, and will provide a default parameter of {} instead - whose destructured properties will then get default-assigned properly. Otherwise, if the function is called without any parameters, it will result in an error:

class GuitarAmp1 {
    constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' } = {}) {
      console.log(cabinet);
   }
}
class GuitarAmp2 {
    constructor ({ cabinet = 'spruce', distortion = '1', volume = '0' }) {
      console.log(cabinet);
   }
}
new GuitarAmp1();
new GuitarAmp2();

This default-parameter-deconstruction pattern can be used for any function, whether it's a constructor or not.

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

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.