ES6 introduces a new way of assigning properties to an Object Literal to save us some of those precious keystrokes along with some fancy way of assigning computed properties.

Property Shorthand

If you’re familiar with C#, you’ll no doubt have seen the same feature when using .NET Anonymous Type and Dynamic.

If you want to assign a property with the same name that it’s already declared in, you can no do this using shorthand property assignment.

1
2
3
let x = 1, y = 2
let point = { x, y }
console.log(point) // { x : 1, y : 2 }

Here’s another example demonstrating a function being assigned to an Object Literal with shorthand.

1
2
3
let sayHello = (name) => { console.log(`Hello ${name}`) }
let myObj = { sayHello }
myObj.sayHello('Martin') // Hello Martin

Computed Property Name

ES6 allows declaring a property that is evaluated during declaration.

1
2
3
4
5
let obj = {
  name : 'David',
  ['sayHelloTo' + name]: () => { console.log(`Hello ${name}`) }
}
obj.sayHelloToDavid() // Hello David

Because the property name is computed during declaration, you can’t try to change it after it’s already been declared.

1
2
3
4
5
6
7
let obj = {
  name : 'David',
  ['sayHelloTo' + name]: () => { console.log(`Hello ${name}`) }
}
obj.sayHelloToDavid() // Hello David
obj.name = 'Andy'
obj.sayHelloAndy() // error: sayHelloAndy is not a function

This feature simply gives a shorthand way of doing the same thing in ES5 by assignment the property after the object is created:

1
2
3
4
5
6
7
8
9
var obj = {
  name : 'David'
}

obj['sayHelloTo' + obj.name] = function() {
  console.log('Hello ' + obj.name)
}

obj.sayHelloToDavid()

I was actually a bit confused as for the use case for the computed property name feature, but there is one particular use case that seems compelling, as answered on stackoverflow.

This could be used for when the object that we want needs to be passed to somewhere else e.g. an API and we want to create the objects in such a way that we can redefine the property names by just changing some constant values rather than changing them directly making it more difficult to maintain.

Method Properties

Method Properties allow a way of declaring methods directly to an object literal without the need for defining it as a function as you would previously in ES5.

1
2
3
4
5
6
let obj = {
  name : 'David',
  sayHello() { console.log(`Hello ${this.name}`) }
}

obj.sayHello()

This can be done the same way in ES5 like this:

1
2
3
4
5
6
var obj = {
  name: 'David',
  sayHello: function() { console.log('Hello ' + this.name) }
}

obj.sayHello()

We’ve just saved ourselves 12 keystrokes by getting rid of : function().

Note that this also works for ES6 classes.

1
2
3
4
5
6
7
8
9
10
11
12
class Person {
  constructor(name) {
    this.name = name
  }
  
  sayName = () => {
    console.log(this.name)
  }
}

let david = new Person('David')
david.sayName() // David