Today I saw a piece of code which I have never seen before:
var a = 1;
var b = 2;
var c = { a, b };
This creates an object (assigned to c) which contains two keys, those are the names of the variables, and the values are the variable's values, like this:
{
a: 1,
b: 2
}
Is this something normal? I couldn't find anything related to this or creating objects this way. I tested it on chrome and it worked fined, but I am not sure if this will work in every browser.
I would expect to create the object this way:
var c = { a: a, b: b };
This is part of the ES6 object shorthand, where you may use variables from the current scope to declare a property within an object (literal) with the same name and value as that variable.
That is, c = {a, b}
expands to c = {a: a, b: b}
so long as a
and b
are both in the current scope.
The MDN documentation goes into more detail here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With