DEV Community

loading...

Write Concise Declarative Functions with ES6

rthefounding profile image Randy Rivera ・1 min read
  • When defining functions within objects in ES5, we have to use the keyword function as follows:
const bicycle = {
  gear: 2,
  setGear: function(newGear) {
    this.gear = newGear;
  }
};
Enter fullscreen mode Exit fullscreen mode

With ES6, you can remove the function keyword and colon altogether when defining functions in objects. Here's an example of this syntax: Here we just refactored the function setGear inside the object bicycle and used the shorthand syntax.

const bicycle = {
  gear: 2,
  setGear(newGear) {
    this.gear = newGear;
  }
};

bicycle.setGear(3);
console.log(bicycle.gear); will display 3
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
samuelojes profile image
DGAME

Nice

Forem Open with the Forem app