Arrow functions
Arrow functions provided the following advantagas
- An arrow function expression has a shorter syntax
=>
compared to function expressions.
- Does not bind its own
this
, arguments
, super
, or new.target
.
Arrow functions are always anonymous. The examples are below
Function without any parameters
var intro = () => "Welcome";
console.log(intro());
// The above arrow function is equal to the below vanilla JS function declaration
var intro = function () { return "Welcome"; };
console.log(intro());
Function with 1 parameter
var multiplyBy2 = value1 => value1 * 2;
console.log(multiplyBy2(4)); // prints 8
// The above arrow function is equal to the below normal function declaration
var multiplyBy2 = function (value1) { return value1 * 2; };
console.log(multiplyBy2(4)); // prints 8
Function with more than 2 parameters
var add = (value1, value2) => value1 + value2;
console.log(add(10, 20)); // prints 30
// The above arrow function is equal to the below normal function declaration
var add = function (value1, value2) { return value1 + value2; };
console.log(add(10, 20)); // prints 30
this reference
An arrow function does not create its own this context, so this has the original meaning from the enclosing context.
Working with this
until ES5 (old way)
function Person() {
var _this = this;
this.count = 0;
setInterval(function () {
console.log(_this.count++); // |this| properly refers to the person object
}, 1000);
}
Es6 Arrow function implementation.
function Person(){
this.count = 0;
setInterval(() => {
console.log(this.count++); // |this| properly refers to the person object
}, 1000);
}