Table of contents
No headings in the article.
Arrow functions are the same as regular functions but there are some very important differences.
- Main differences are
- Syntax
- Arguments binding>
- Use of this keyword
- Using a new keyword
- No duplicate named parameters
Let me explain with an example
Syntax
Arrow Function is also called fat arrow function is a new feature which is introduced in ES6 is the more concise syntax for writing a function expression.
// Regular Function Syntax ES5:
var add = function(x, y) {
return x + y;
};
// Arrow function ES6
let add = (x, y) => { return x + y };
In above example arrow symbol( =>) replaces keyword function
let add = (x,y) => x + y
curly brackets are not required if only expressions are there
Arguments binding
Arrow function do not have argument binding where as Regular function have Argument binding .
*example
// Object with Regular function.
let getData = {
// Regular function
showArg:function(){
console.log(arguments);
}
}
getData.showArg(1,2,3); // output {0:1,1:2,2:3}
Arrow function
// Object with Arrow function.
let getData = {
// Arrow function
showArg:()=>console.log(arguments)
}
getData.showArg(1,2,3); // Uncaught ReferenceError: arguments is not defined
Use of this keyword
- Arrow function does not have their own this
let name ={
fullName:'shubham Kumar',
printInRegular: function() {
console.log(`My Name is ${this.fullName}`);
},
printInArrow:()=>console.log(`My Name is ${this.fullName}`)
}
name.printInRegular();
name.printInArrow()
Using a new keyword
Regular functions created using function declarations or expressions are constructible and callable. Regular functions are constructible; they can be called using the new keyword.
However, the arrow functions are only callable and not constructible, i.e., arrow functions can never be used as constructor functions.
Example:
const sum = function (x,y) {
console.log(x+y)
}
new sum(4,5)
output : 9
Arrow function
const sum => (x,y) => console.log(x,y)
sum( 4,5) // Uncaught TypeError: sum is not a constructor
at <anonymous>:1:1
No duplicate named parameters
Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.
However, We can use duplicate named parameters for regular function in non-strict mode
That's it folks, Hope you are like it , feedback are welcome