Reputation: 15362
I was reading an ES2015 primer on this site and this example was given for computed property names:
const namespace = '-webkit-';
const style = {
[namespace + 'box-sizing'] : 'border-box',
[namespace + 'box-shadow'] : '10px10px5px #888888'
};
This is pretty straightforward, but I don't understand what Babel is doing it to transpile it. It gives this:
var _style;
var namespace = '-webkit-';
var style = (
_style = {},
_style[namespace + 'box-sizing'] = 'border-box',
_style[namespace + 'box-shadow'] = '10px 10px 5px #888888',
_style
);
(I've reformatted the indentations)
Online Babel Transpilation here
I cannot find documentation on what this syntax is: the declaration of the _style
object, then a list in paranthesis of property names and their values, then simply ending with a, _style
before the ending parthenthesis.
Upvotes: 3
Views: 78
Reputation: 239443
In JavaScript, the expressions in parenthesis, because of the comma operator, are executed from left-right and the result of the last expression will be returned as the result. For example,
console.log(
(console.log(1), console.log(2), 3)
);
would print 1, 2, and 3 in three lines. The last value 3
is returned as the result of the expression and that is printed by the outer console.log
.
Same way,
var style = (
_style = {},
_style[namespace + 'box-sizing'] = 'border-box',
_style[namespace + 'box-shadow'] = '10px 10px 5px #888888',
_style
);
Here,
_style = {},
creates an object and assigns it to _style
,
_style[namespace + 'box-sizing'] = 'border-box',
creates a new property namespace + 'box-sizing'
and assigns a value to it,
_style[namespace + 'box-shadow'] = '10px 10px 5px #888888',
same as above, and finally, _style
will be returned as the result of evaluation.
At the end, you get an object with two properties and that is bound to the variable style
.
Upvotes: 6