Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Javascript Object without explicitly defining the keys? [duplicate]

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 };
like image 988
Pablo Matias Gomez Avatar asked Feb 06 '23 12:02

Pablo Matias Gomez


1 Answers

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.

like image 151
ssube Avatar answered Feb 11 '23 00:02

ssube