Rikard
Rikard

Reputation: 7805

Square brackets notation inside object definition

In JavaScript we can access or create Object properties dynamically by using []. Is it documented that one also can use it while defining/creating the object?

As far as I tested (Chrome, FF, Safari) latest versions this works good. Is this documented, did old browsers also support this?

var key = "foo";
var value = 'bar';
var object = {
    a: 1,
    b: 2,
    [key]: value,
    c: 3
};

document.body.innerHTML = JSON.stringify(object); // {"a":1,"b":2,"foo":"bar","c":3}

http://jsfiddle.net/o2x6chzd/

Upvotes: 2

Views: 127

Answers (2)

Ben Aston
Ben Aston

Reputation: 55729

Yes. It's called a computed property name and is new in ES2015.

It means you can add object properties with runtime-chosen names in the same lexical construction as the object instance creation.

Previously you had to add properties with runtime-computed names after object instantiation.

Expressions can be used to compute the name:

function foo() { return 1; }
var o = {
  [foo() + 1]: 'should be 2'
};
console.log(o); // Object {2: "should be 2"}

Upvotes: 3

KAD
KAD

Reputation: 11112

Starting with ECMAScript 6, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed as the property name.

Check the documentation.

Upvotes: 3

Related Questions