DEV Community

Mohana Naga Venkat Sayempu
Mohana Naga Venkat Sayempu

Posted on

Object Literal Enhancements

Object literal syntax has received a number of enhancements in es6.

Property Initialiser Shorthand

When a new object literal is created and populated with properties of the same name that exist in the current scope then a shorthand syntax can be used.

var foo = 'foo';
var bar = 'bar';

var o = {foo, bar};

console.log(o); // {foo: 'foo', bar: 'bar'}

Method Initialiser Shorthand

Methods can now be declared in object literals in a similar way to the new class construct.

var o = {
  foo () {
  }
};

console.log(o); // {foo: [Function]}

Computed Property Names

Dynamic property names can be used while creating object literals.

var foo = 'foo';

var o = {
  [foo]: 'bar',
  [new Date().getTime()]: 'baz'
};

console.log(o); // {foo: 'bar', 1428942731913: 'baz'};

Native object merging

The new Object.assign function copies properties and methods from source objects into the leftmost target object and returns it.

var o1 = {foo: 'foo'};
var o2 = {bar: 'bar'};
var o3 = {baz: 'baz', foo: 'qux'};

Object.assign(o1, o2, o3); // {foo: 'qux', bar: 'bar', baz: 'baz'}
console.log(o1); // {foo: 'qux', bar: 'bar', baz: 'baz'}

Happy Coding 😀

Top comments (0)