12 Jun 2019

JavaScript Arrow Function

Arrow functions allow shorter syntax, for example:

const foo = () {
    return "bar";
}

vs

const foo = () => {
    return "bar";
}

or even

const foo = () => "bar";

If a function has only one parameter you can skip the parentheses:

const timesTwo = val => 2 * val;

Handling this

→ In regular functions this keyword represents the object that called the function.

→ In arrow functions this keyword represents the object that defined the arrow function.

Regular function:

javascriptCopy code
const obj = {
  name: 'John',
  regularMethod: function() {
    console.log(this.name);
  }
};
obj.regularMethod(); // Output: John

Arrow function:

javascriptCopy code
const obj = {
  name: 'John',
  arrowMethod: () => {
    console.log(this.name);
  }
};
obj.arrowMethod(); // Output: undefined (the arrow function inherits the `