Melissa Gonzalez
By Melissa Gonzalez

JavaScript Arrow Functions

JavaScript Arrow Functions

Arrow Functions

An arrow function expression has a shorter syntax compared to regular functions expressions. There are two key differences: arrow functions are always anonymous and are non-binding of ‘this’.

Before:

1
2
3
4
5
6
7
hello = function() {

  return "Hello World!";

};

After:

1
2
3
4
5
6
7
hello = () => {

  return "Hello World!";

};

It can be even shorter if the function has only ONE statement that returns a value.

Example:

1
2
3
hello = () => "Hello World!";

How to Use Parameters

1
2
3
hello = (param) => "Hello " + param;

OR without parenthesis

1
2
3
hello = (param) => "Hello " + param;

How to Handle ‘this’

Regular functions always define its ‘this’ value but arrow functions treat ‘this’ keyword differently. They do not define their own context since it doesn’t have its own ‘this’ context. It is inherited from the parent scope whenever you call ‘this’.

Example:

Regular Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var obj = {

  count: 10,

  doSomethingLater: function() {

    setTimeout(function() {

      // the function executes on the window scope

      this.count++;

      console.log(this.count);

    }, 300);

  },

};



obj.doSomethingLater(); // result is "NaN", because the property "count" is not in the window scope.

Arrow Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var obj = {

  count: 10,

  doSomethingLater: function() {

    // The traditional function binds "this" to the "obj" context.

    setTimeout(() => {

      // Since the arrow function doesn't have its own binding and

      // setTimeout (as a function call) doesn't create a binding

      // itself, the "obj" context of the traditional function will

      // be used within.

      this.count++;

      console.log(this.count);

    }, 300);

  },

};



obj.doSomethingLater();