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 System Overview
  2. JS: What's Object?
  3. JS: Prototype and Inheritance
  4. JS: Create Object
  5. JS: Object Literal Expression
  6. JS: Get/Set Prototype
  7. JS: How to Create Object with Parent X?
  8. JS: Prevent Adding Property
  9. JS: Determine Type of Object
  10. JS: Primitive Value Object Wrapper
  11. JS: Clone, Deep Copy Object/Array
  12. JS: Test Equality of Objects

  1. JS: Object Object
  2. JS: Object.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon