ES2015Objects
devguides.io / ES2015

Objects

ES2015 offers some shorthand for writing object Names, Functions, Getters and setters, and Computed name properties.

App = {
  handler,

  Functions:
  start () { return this.go() },

  Getters and setters:
  get closed () { return this.status === 'closed' },
  set closed (val) { this.status = val ? 'closed' : 'open' },

  Computed properties:
  [ 'prop_' + n ]: 42
}

What's handler up there mean? Next

Name shorthand

Ever type { foo: foo } and find it repetitive? This is common when writing exports. You can now shorten this in ES2015.

module.exports = {
  update: update,
  save: save
}
module.exports = { update, save }

update rolls out into update: update.


You can use this shorthand anywhere in a {...} object.

module.exports = { update, save, create: createItem }

You can shorten functions, too. Next

Function shorthand

JavaScript lets you define properties as functions. You can now shorten this in ES2015.

App = {
  start: function () {  }
}
App = {
  start () {  }
}
App.start()

Learn about getters and setters. Next

Getters and setters

Apart from function shorthands, you can define special attributes that do something when read or set.

Shop = {
  get closed () {
    return this.status === 'closed'
  },
  set closed (value) {
    this.status = value ? 'closed' : 'open'
  }
}
Shop.closed = true  invokes set closed()
Shop.status         'closed'
Shop.closed         true (invokes get closed())

Also see: get (MDN)

Learn about writing dynamic property names. Next

Computed names

You can write properties with key names derived from expressions.

let id = 'john'
let Users = { [id]: 'John Frobisher' }
Users.john  'John Frobisher'

You would've written it like the long way in ES5:

var id = 'john'
var Users = {}
Users[id] = 'John Frobisher'

This works with the other function shorthands, too. This example creates a function gettitle().

var key = 'title'
App = {
  ['get' + key]() { return this[key] }
}

Let's recap what we've learned. Next

Recap

ES2015 offers some shorthand for writing object Names, Functions, Getters and setters, and Computed name properties.

App = {
  handler,

  Functions:
  start () { return this.go() },

  Getters and setters:
  get closed () { return this.status === 'closed' },
  set closed (val) { this.status = val ? 'closed' : 'open' },

  Computed names:
  [ 'prop_' + n ]: 42
}

Let's learn about classes. Next chapter