JavaScript: 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:

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 property key that is symbol. 〔►see JavaScript: Symbol Tutorial

Method Syntax Shorthand

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

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

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

Object and Inheritance Topic

  1. JavaScript: Object System Overview
  2. JavaScript: What's Object?
  3. JavaScript: Prototype and Inheritance
  4. JavaScript: Create Object
  5. JavaScript: Object Literal Expression
  6. JavaScript: Find Object's Prototype
  7. JavaScript: How to Create Object with Parent X?
  8. JavaScript: Prevent Adding Property
  9. JavaScript: Determine Type of Object
  10. JavaScript: Primitive Value Object Wrapper
  11. JavaScript: Clone, Deep Copy Object/Array
  12. JavaScript: Test Equality of Objects

  1. JavaScript: Object Object
  2. JavaScript: Object.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.