Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 567
JustGoscha Avatar asked Jun 01 '16 09:06

JustGoscha


1 Answers

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.

like image 139
Marc Dix Avatar answered Nov 06 '22 11:11

Marc Dix