Fat arrow function concept is introduced in ES6.
Normal Function Syntax
var add = function(x, y) {
return x + y;
};
Arrow Function
let add = (x, y) => {
return x + y
};
Difference 1 – Way of writing
For single expression, we don’t need parenthesis or even return keyword in fat arrow function
Normal Function | Fat Arrow Function |
// const a = function (x, y) { // return x + y; // }; // console.log(a(2, 3)); | const a = (x, y) => x + y; console.log(a(2, 3)); For single parameter : ——————— const a = x=> x*x; console.log(a(2)); |
Difference 2 – Argument Binding
Arrow function does not have argument bindings
Normal Function | Fat Arrow Function |
const a = function () { console.log(arguments); }; a(1, 2, 3); | const a = () => { console.log(arguments); }; a(1, 2, 3); Output – error |
Difference 3 – Use of new keyword . Constructible or not ?
In normal function , we can create constructor, thus it can be called by new keyword
In arrow function , we cannot create constructor, hence function cannot be invoked by new keyword
Normal Function | Fat Arrow Function |
let c = function () { console.log(“hello”); }; new c(); | let c = () => { console.log(“hello”); }; new c(); Output – error Output – Uncaught TypeError: c is not a constructor |
Difference 4 : this keyword
Important - Arrow function does not have its own this. "this" in arrow function is always bound to the closest this of the parent non arrow function.
//closest non-arrow function
let him = {
name: "himanshu",
};
let user = {
name: "what about coding",
wac1: () => {
console.log("hello " + this.name); // no 'this' binding here
},
wac2() {
console.log("Welcome to " + this.name); // 'this' binding works here
},
};
user.wac1();
user.wac2();
Source - gfg
Difference 5 : Duplicate Name Parameter
In arrow function argument with same name is not allowed
Normal Function | Fat Arrow Function |
function add(x, x) { console.log(x); } add(2, 4); Output – works fine | add = (x, x) => { console.log(x); }; add(2, 4); Output – error Output – Uncaught SyntaxError: duplicate argument names not allowed in this context |
Found the article helpful , please share it with the needy.
Follow me – Instagram