ES6 - Arrow Functions
Arrow functions are one of the more popular features of ES6 saving developer time and simplifying function scope.
- The arrow
(=>)orfat arrowprovides a shorthand for the function keyword with lexicalthisbinding- Arrow functions change the way
thisbinds in functions - They work much like
lambdasin languages likeC#orPythonlambdaexpressions are are often passed as arguments to higher order functions
- we avoid the
functionkeyword,returnkeyword andcurly bracketswhen using arrow functions
- Arrow functions change the way
- Arrow functions allow developers to remove boilerplate, however you shouldn’t remain ignorant of how ‘lexical
scopingthis` works - Be careful when using
arrow functionsas they aren’t applicable everywhere, use cases will depend from situation to situation
For the sake of simplicity, we could do the following:
const msg = () => alert("Hello Arrow Function");
console.log(msg());
let square = ( a, b ) => a * b;
console.log(square(5, 5)); // 25
let x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let z = x.map(x => x);
console.log(z); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
Every new function defines it’s own this value, yet arrow functions close over the this value
// in ES5
function Tree() {
that = this;
that.age = 0;
setInterval(function growOld() {
that.age++;
}, 1000);
}
var t = new Tree();
// in ES6
function Tree() {
this.age = 0;
setInterval(() => {
this.age++;
5000);
}
}
var t = new Tree();