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.

// evaluate a variable as property key
const xx = "bb";
const jj = { [xx]: 4 };
console.log(jj["bb"] === 4);
// compute a property key at runtime
const jj = { ["a" + "b"]: 4 };
console.log(jj.ab === 4);

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 jj = {
  f(x) {
    return x + 1;
  },
  g: 4,
};

console.log(jj.f(2) === 3);
BUY ΣJS JavaScript in Depth