6

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

5
  • The second code is the correct Commented Jun 1, 2016 at 9:46
  • But the first works. Try it in your console Commented Jun 1, 2016 at 9:47
  • 2
    The first version (with brackets) was introduced in ES6 and is now accessible in some newer browsers e.g. current version of Chrome. Current best practice is to compile ES6 Javascript to ES5 version via e.g. babel.js or other transcompilers so if you want to deploy this code to web it is better to stick with ES5 and use second syntax or to go with ES6 and use transcompilation Commented Jun 1, 2016 at 9:50
  • Yeah, but then what's the exact question? Commented Jun 1, 2016 at 9:50
  • The exact question was since when it's supported Commented Jun 1, 2016 at 10:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.