Difference Between Arrow Funtion and Fegular Function
Arrow funtion sometimes called fat arrow function. it intorduce in 2015. Fat arrow function is more concise syntax for writing function than regular function.
Following are the main differences:
- Syntax
- Arguments binding
- Use of this keyword
- Using a new keyword
- No duplicate named parameters
1. Syantax: Arrow function syntax writing is more handy than regular funtion.
2. Argument binding:
Arrow function dosent support argument binding but regular funtion does.
regular function:
function showData(){
console.log(...arguments)
}
showData(1, 2, 3)
let showData=()=>{
console.log(...arguments)
}
showData(1,2,3)
3. Use of this keyword
Inside of a regular JavaScript function, this value is dynamic.
The dynamic context means that the value of this depends on how the function is invoked. In JavaScript, there are 4 ways you can invoke a regular function.
unlike Regular functions, arrow function does not have their own "this" keyword.
let name ={
fullName:'Vandna Kapoor',
printInRegular: function(){
console.log(`My Name is ${this.fullName}`);
},
printInArrow:()=>console.log(`My Name is ${this.fullName}`)
}
name.printInRegular();
name.printInArrow();
$ node index.js
My Name is Vandna Kapoor
My Name is undefined
4. Using a new keyword
Regular function are callabe and constructable using new keyword but arrow function only callable i.e
arrow functions can never be used as constructor functions.
Regular function
function add(x,y){
console.log(x+y)
}
new add(2,5)
//7
Arrow funtion
let add=(x,y)=>{
console.log(x+y)
}
new add(2,5)
// Error
5. No duplicate named parameters
Arrow function dosent support duplicate parameter but regular function does.
function add(x,x){
console.log(x+x)
}
add(10,5)
// 10