# Arrow functions
- Arrow functions are one of the most popular features of ES6
- Arrow functions make your code more readable and (much) shorter but they behave differently compared to the regular ES5 functions
- Converting a regular ES5 function (expression) to an ES6 arrow function is easy:
- remove the
function
keyword - add a fat arrow
=>
between()
and{}
- remove the
// ES5 function expression
const sum = function (a, b) {
return a + b;
};
// ES6 arrow function
const sum = (a, b) => {
return a + b;
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# Shorthands
# Single parameter
- For a single parameter functions, parentheses are optional
const squareRoot = (number) => {
return Math.sqrt(number);
};
// shorthand
const squareRoot = number => {
return Math.sqrt(number);
};
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Single statement
- For a single statement functions, the curly braces, and the
return
keyword are optional
const squareRoot = (number) => {
return Math.sqrt(number);
};
// shorthand
const squareRoot = number => Math.sqrt(number);
1
2
3
4
5
6
7
2
3
4
5
6
7
# this keyword
- There is a huge difference between the meaning of the
this
keyword inside regular ES5 functions and inside ES6 arrow functions! - Open es6/functions/this.html and es6/functions/this.js
- Regular function:
this
refers to the clicked button - Arrow function:
this
refers to the globalwindow
object, so you have to usee.target
to refer to the clicked button
- Regular function:
REMARKS
- In the example above, we used an anonymous/nameless arrow function as callback function for the event listener:Likewise, we can do so for the callbacks in the timing functions:
<element>.addEventListener('<event>', (e) => { ... });
1setTimeOut( () => { ... }, 1000); setInterval( () => { ... }, 1000);
1
2 - Because the meaning of the
this
keyword inside arrow functions, it's not advisable to use arrow functions as methods inside classes and objects (see later)
READING/WATCHING TIPS
# Exercises
- Open exercises/index.html and make the exercises under the tab ES6 > (Timing, user-defined and arrow) Functions