Arrow functions were introduced in ES6 (EcmaScript 6) which provides the more compact way to work with anonymous functions with smaller and compact syntax making code more readable and structured.
Though, arrow functions provide compact and short hand syntax to define functions, following are limitations
- Arrow functions can not be used as methods since they don’t have their own binding such that following are not available in the arrow function that is, this, arguments and super
- Arrow functions are not suitable to be used as constructors
- Arrow functions can not be used as generators that you cannot use yield keyword inside
- Arrow functions can’t be used with call, apply and bind methods
- Arrow functions can not access new.target keyword
Apart from limitation of arrow functions, there is an advantage with using arrow function is that, execution context will be the execution context of outer function/method. Thus, this keyword would be reference to the this of outer function
Syntax of Arrow function
Arrow function with out parameters
() => expression
Arrow function with single or multiple parameters
param => expression
(param1, param2) => expression
Arrow function with multiple lines of code
(param1, param2) => {
// Statements
}
Assign arrow function to a variable
var sum = (a, b) > a+b
sum(2, 3)
Arrow function vs traditional function
//Normal Function
function addDiscount(p, discount) {
let final_price = p - ((discount/100) * p )
return final_price;
}
// Arrow Function
const addDiscount = (p, discount) => p - ((discount/100) * p )
.
Following code demonstrates that execution context for arrow function and outer function is same. That is, this keyword inside arrow refers to this of outer function
class Foo {
constructor() {
console.log("ok")
}
bar () {
console.log("This at bar ", this);
// Arrow function
let arrowfunc = () => console.log("This is at arrow", this);
arrowfunc();
}
}
var obj = new Foo()
obj.bar()
output:
This at bar Foo {}
This is at arrow Foo {}
As per the above example, we can see that “this” keyword would be referring to same object as outer function of arrow function referring to. We can take advantage of this feature to pass callbacks to asynchronous function where which are called with outer function execution context
Leave a Reply