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