ES6 - Arrow Functions
Arrow functions are one of the more popular features of ES6
saving developer time and simplifying function scope.
- The arrow
(=>)
orfat arrow
provides a shorthand for the function keyword with lexicalthis
binding- Arrow functions change the way
this
binds in functions - They work much like
lambdas
in languages likeC#
orPython
lambda
expressions are are often passed as arguments to higher order functions
- we avoid the
function
keyword,return
keyword andcurly brackets
when using arrow functions
- Arrow functions change the way
- Arrow functions allow developers to remove boilerplate, however you shouldn’t remain ignorant of how ‘lexical
scoping
this` works - Be careful when using
arrow functions
as 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();