FrontendDeveloper.in

ECMAScript question detail

Enhanced object literals

Object literals are extended to support setting the prototype at construction, shorthand for foo: foo assignments, defining methods, making super calls, and computing property names with expressions.

The important enhancements of object literals are,

  1. Property Shorthand:

Object's properties are often created from variables with the same name.

Let's see the ES5 representation

var a = 1, b = 2, c = 3,
obj = {
a: a,
b: b,
c: c
};
console.log(obj);

and it can be represented in a shorter syntax as below,

const a = 1, b = 2, c = 3;
const obj = {
a,
b,
c
};
console.log(obj);
  1. Method Shorthand: In ES5, Object methods require the function statement as below,
var calculation = {
sum: function(a, b) { return a + b; },
multiply: function(a, b) { return a * b; }
};

console.log(calculation.sum(5, 3));  // 8
console.log(calculation.multiply(5, 3)); // 15

This can be avoided in ES6,

const calculation = {
sum(a, b) { return a + b; },
multiply(a, b) { return a * b; }
};

console.log(calculation.sum(5, 3));  // 8
console.log(calculation.multiply(5, 3)); // 15
  1. Computed Property Names: In ES5, it wasn’t possible to use a variable for a key name during object creation stage.
var
key = 'three',
obj = {
one: 1,
two: 2
};

obj[key] = 3;

Object keys can be dynamically assigned in ES6 by placing an expression in square brackets([])

const
key = 'three',
computedObj = {
one: 1,
two: 2,
[key]: 3
};
Back to all ECMAScript questions
Get LinkedIn Premium at Rs 399