Read more

Shorthand function properties in ES6

Henning Koch
July 09, 2020Software engineer at makandra GmbH

Here is an ES5 object literal with two string properties and a function property:

let user = { 
  firstName: 'Max',
  lastName: 'Muster',
  fullName: function() { return this.firstName + ' ' + this.lastName }
}

user.fullName() // => 'Max Muster'
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

In ES6 we can define a function property using the following shorthand syntax:

let user = { 
  firstName: 'Max',
  lastName: 'Muster',
  fullName() { return this.firstName + ' ' + this.lastName }
}

user.fullName() // => 'Max Muster'

We can also define a getter inside the object literal, without using Object.defineProperty():

let user = { 
  firstName: 'Max',
  lastName: 'Muster',
  get fullName() { return this.firstName + ' ' + this.lastName }
}

user.fullName // no parentheses
Posted by Henning Koch to makandra dev (2020-07-09 14:50)