Arrow functions and 'this' Keyword

in es6 functions can be rewritten in several ways using arrow functions

Ways to write arrow functions

one line of code


var fn = () => console.log('hello');


1
2
3
4

one line of code


var fn = () => 'Hello';

console.log(fn())

1
2
3
4
5

Multiple lines of code


var fn = () => {
  let a = 2;
  let b = 5;
  return a + b;

};

console.log(fn())

1
2
3
4
5
6
7
8
9
10

Passing multiple arguments


var fn = (a, b) => {
  return a + b;

};

console.log(fn(3, 8))

1
2
3
4
5
6
7
8

Passing multiple arguments


var fn = (a, b) => a + b;

console.log(fn(3, 8))

1
2
3
4
5

Passing only one argument


var fn = (a) => a + 5;

console.log(fn(3))

1
2
3
4
5

Passing only one argument allows you to leave out the parenthases


var fn = a => a + 5;

console.log(fn(3))

1
2
3
4
5

Using a callback


setTimeout(() => console.log('Hello'), 1000);

1
2
3

Arrow functions and 'this'

Note arrow functions treat 'this', differently.

Example one

Both will log the global window object


//Old
function fn() {
console.log(this);
}

// arrow

var fn2 = () => console.log(this);

console.log(fn())

console.log(fn2())

1
2
3
4
5
6
7
8
9
10
11
12
13
14

Example 2

Arrow functions always retain their context regardless of where they were defined for example in the following snippet you will notice that the old 'es5' way changes its context based pm the action that called the function, while the fat arrow function retains its context () the global window object.


<button>Click me with the console open</button>

1
2
3

//Button
var button = document.querySelector('button');

//Add the event listener
button.addEventListener('click', {
fn();
fn2();
})

//Arrow function - retains 'this' context
var fn2 = () => console.log(this);

//ES5 - Changing 'this' context
function fn() {
  console.log(this);
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Last Updated: 8/13/2019, 6:55:26 PM