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; },
    g:4
};

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

Reference

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

JS Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Prototype and Inheritance
  4. Create Object
  5. Object Literal Expression
  6. Create Object with Parent X
  7. Get/Set Prototype
  8. Prevent Adding Property
  9. Determine Type of Object
  10. Clone Object
  11. Test Object Equality
  12. Add Method to Prototype
  13. Object Object
  14. 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.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog