JavaScript: Object Literal Expression Extensions (ES2015)

By Xah Lee. Date: . Last updated: .

Computed Property Key

ES2015 introduced a new notation for literal expression of object , so that the property key part can be a variable or expression. Use square bracket around the property key. Like this:

var obj = {[expression]:value}

This is called “computed property key”.

// es2016 computed property syntax. use [] around the property key
var obj = {["a" + "b"]: 4 };
console.log(obj.ab); // 4

The expression for the property key can be just a variable name.

// computed property key
var x = "cc";
var obj = {[x]: 3};
console.log(obj.cc); // 3

This new syntax is especially useful for ES2015 symbol property. 〔➤see JavaScript: Symbol (ES2015)

Method Syntax Shorthand

var obj = { method_name() { … }, … };

is equivalent to

var obj = { method_name: function () { … }, … };

// new syntax shorthand for method, ES2015
var obj = {
    f(x) { return x + 1; },
    g:4
};

console.log( obj.f(2) ); // 3

Reference

ES2015 §ECMAScript Language: Functions and Classes#sec-method-definitions

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.