Arrow functions are a concise syntax introduced in ES6 that do not have bindings to 'this', 'arguments', 'super', or 'new.target'. They can be used in various contexts, support rest and default parameters, destructuring, and are suitable for callbacks in functions like map, filter, and promises. However, arrow functions cannot be used as constructors and do not have a local 'arguments' value.
Arrow function syntax(2)
// Parentheses are optional when there's only one
parameter name:
5. (singleParam) => { statements }
6. singleParam => { statements }
// The parameter list for a function with no parameters
should be written with a pair of parentheses.
7. () => { statements }
6.
Arrow function syntax(3)
// Parenthesize the body of a function to return an object literal
expression:
8. params => ({foo: bar})
// Rest parameters and default parameters are supported
9. (param1, param2, ...rest) => { statements }
10. (param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }
7.
Arrow function syntax(4)
// Destructuring within the parameter list is also
supported
11. const f = ([a, b] = [1, 2], {x: c} = {x: a + b}) =>
a + b + c;
f(); // 6
8.
Regular functions
const f= function (param1, param2, … paramN) { statements }
function f(param1, param2, … paramN) { statements }
9.
Regular function VSArrow function
Regular functions have their own this binding, arrow functions
lexically bind the this value.
// Regular function
const House = function () {
this.rent = 100;
setInterval( function () {
console.log(this.rent = this.rent * 2);
}, 1000);
}
const house = new House();
// NaN
// NaN
// NaN
// NaN
// Regular function, how to make it work 1
const House = function () {
let self = this;
self.rent = 100;
setInterval( function() {
console.log(self.rent = self.rent * 2);
}, 1000);
}
const house = new House();
// 200
// 400
// 800
10.
Regular function VSArrow function
// Regular function, how to make it work 2
const House = function () {
this.rent = 100;
setInterval( function () {
console.log(this.rent = this.rent * 2);
}.bind(this), 1000);
}
const house = new House();
// 200
// 400
// 800
// 1600
// Arrow function
const House = function () {
this.rent = 100;
setInterval( () => {
console.log(this.rent = this.rent * 2);
}, 1000);
}
const house = new House();
// 200
// 400
// 800
// 1600
11.
Regular function VSArrow function
Arrow functions cannot be used as constructors.
Arrow functions don’t have the local arguments value.
Arrow functions are anonymous similar to lamda
functions in other languages.
12.
How I useArrow functions
When I want to write less and expressive
let double = x => x*2;
With map, filter, reduce
let doubleList = [2, 4, 6].map(x => x*2);
13.
How I useArrow functions
As callback to api, function calls, and promises
new Promise( (success, faillure) => { … });
To make use of this without stress in class methods
class House {
id = "1";
house = "";
info() {
ApiCall.get(id).then( house => this.house = house);
}
}