##When and where should we use normal function as opposed to arrow function ?##
"this" binding
Unlike regular functions, arrow functions don’t have their own this or arguments binding. Instead, those identifiers are resolved in the lexical scope like any other variable
“arguments” binding
Arguments objects are not available in arrow functions, but are available in regular functions.
Regular function:
let myFunc = {
showArgs(){
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);
Arrow function:
let myFunc = {
showArgs : ()=> {
console.log(arguments);
}
};
myFunc.showArgs(1, 2, 3, 4);// error
Arrow functions cannot be called with “new"
If a function is constructible, it can be called with new. If a function is callable, it can be called without new.
Regular functions created through function declarations / expressions are both constructible and callable.
Arrow functions are only callable i.e arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.
When Not to Use Arrow Function
Here are few cases where you shouldn't look at arrow function:
1:)Object methods
var david = {
burger: 3,
eatBurger: () => {
this.burger--;
}
}
When you call david.eatBurger, the number of burgers does not decrease. It is because this is not bound to anything, and will inherit the value of this from its parent scope.
2:) When it makes your code less readable
. With regular functions, people know what to expect. With arrow functions, it may be hard to decipher what you are looking at straight away.
Top comments (0)