2

I saw the following ES6 code and was confused:

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

What is the second parameter to Object.assign? It's not an object, so what is it? I just noticed it's part of the constructor arguments too, this part:

{ cabinet = 'spruce', distortion = '1', volume = '0' } = {}

I'm unfamiliar with this new syntax so I don't know how to look it up, since I don't know what it's called. Anyone know the term?

temporary_user_name
  • 30,801
  • 41
  • 120
  • 186

3 Answers3

3

So, in the above code, I believe:

{
  cabinet, distortion, volume
}

is in ES5:

{
   cabinet: cabinet,
   distortion: distortion,
   volume: volume,
}

It's just a short form of writing the object, when the key and value are same.

Nevin Madhukar K
  • 2,668
  • 2
  • 19
  • 45
  • Fun fact: this also works for functions. `function myFunction() {}`. `var obj = { myFunction }`. or: `var obj = { myFunction() {} }`. – Jelle den Burger Mar 15 '17 at 08:20
  • 1
    May I note for future readers that this syntax only works with previously declared variables, and does not allow literals.`var d = {'a', 'b', 'c'}` will error. Makes sense. It's just a shorthand for grouping some variables into an object. – temporary_user_name Mar 15 '17 at 08:22
1

The default value of first param is {} but if it is provided, we have nested default values in first param object like cabinet = 'spruce', distortion = '1', volume = '0'

Hence, if first object param is provided with e.g. { cabinet = 'test', distortion = '4', volume = '2' } then, this would be as follows

{ 
  cabinet: 'test', 
  distortion: '4', 
  volume: '2' 
}

otherwise, it will have the default values provided in param.

tanmay
  • 7,042
  • 2
  • 17
  • 35
1

It is an object literal using the shorthand syntax. It is just syntactic sugar.

var a = "A";
var b = "B";
var c = "C";

These two are the same:

{ a: a, b: b, c: c }
{ a, b, c }

In other words, if you throw a variable into the object literal then the property name will become that of the variable name.

Sverri M. Olsen
  • 12,362
  • 3
  • 32
  • 50