justGoscha
justGoscha

Reputation: 24135

Setting dynamic key of new object in JavaScript like { [key] : "value" }

I just found out that it's possible to create an object and set the key dynamically in the curly braces without needing a second line.

var a = "dynamicKey";
var obj = {[a]: "value"}

vs

var a = "dynamicKey";
var obj = {};
obj[a] = "value";

Is this something that was always possible or is in some spec (ES3, ES5)?

Upvotes: 6

Views: 5830

Answers (1)

Marc Dix
Marc Dix

Reputation: 1959

It's called bracket notation and is supported since ES6/JavaScript2015. Also check 'computed property keys' section here. You can also check the ES6/Javascript2015 spec directly (search for 'bracket notation').

ES6/Javascript2015 is currently not supported by all browsers, thus it's best practice to transpile ES6/Javascript2015 to ES5 with tools like babel or to use the old way of setting properties, which you also provided.

Webkit (for example Chrome) is now 100% ES6/Javascript2015 compatible. If you just need to support Chrome/Webkit browsers, you don't have to transpile the ES5 anymore.

Upvotes: 2

Related Questions