JavaScript: ES2015 Object Literal Expression Extensions

By Xah Lee. Date: . Last updated: .

New in JS2015.

Computed Property Key

obj = {[expr]:value}

Eval expr and take result as key.

const obj = {["a" + "b"]: 4 };

console.log( obj.ab === 4 )

This is useful when you want a variable's value to be the property key.

const x = "cc";
const obj = {[x]: 3};
console.log( obj.cc === 3 )

This new syntax is especially useful for property key that is symbol. [see Symbol Tutorial]

Method Syntax Shorthand

obj = { fname() {body} }

is equivalent to

obj = { fname: function () {body}}

const obj = {
    f(x) { return x + 1; },
    g:4
};

console.log( obj.f(2) === 3 );
JS in Depth
XAH  BUY NOW