JS: ES2015 Object Literal Expression Extensions

By Xah Lee. Date: . Last updated: .

New in ES2015.

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:

obj = {[expression]:value}

This is called “computed property key”.

// es2015 computed property syntax. use [] around the property 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.

// computed 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 JS: Symbol Tutorial]

Method Syntax Shorthand

Method syntax shorthand lets you define function in {…} with shorter syntax.

obj = { method_name() { } }

is equivalent to

obj = { method_name: function () { }}

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

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


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

Object and Inheritance Topic

  1. JS: Object Overview
  2. JS: Object Type
  3. JS: Determine Type of Object
  4. JS: Object Literal Expression
  5. JS: Prototype and Inheritance
  6. JS: Create Object
  7. JS: Create Object with Parent X
  8. JS: Get/Set Prototype
  9. JS: Prevent Adding Property
  10. JS: Clone, Deep Copy Object/Array
  11. JS: Test Equality of Objects
  12. JS: Object Object
  13. JS: Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.