Difference Between Arrow Function and Normal Function
Developers can greatly benefit from reused codes when creating software. The use of functions is one method to accomplish this. Functions run code blocks as needed. Normal functions and arrow functions are the two main uses of JS. The two will be contrasted and their respective applications will be covered in this article.
The main difference between arrow functions and normal functions in JavaScript is that arrow functions don't bind their own `this`
value. Instead, they inherit the `this`
binding of the scope in which they are defined. Lets understand with example.
When function refer to objects
Normal Function
When Normal Function refer to objects they bind their own `this`
value.
const human = {
name: "Sourabh",
age: 21,
sayName: function () {
console.log("Normal function : " + this.name);
},
};
human.sayName();
Output:
Normal function : Sourabh
Arrow Function
while In the case of the Arrow function, they don't bind their own `this`
value Instead, they inherit the this
value from the surrounding lexical context (i.e., the scope in which they are defined).
example to illustrate how arrow functions inherit the `this`
binding from the surrounding scope:
// Regular function
function regularFunction() {
console.log("Regular function this:", this);
}
// Arrow function
const arrowFunction = () => {
console.log("Arrow function this:", this);
};
const obj = {
regular: regularFunction,
arrow: arrowFunction
};
regularFunction(); // Regular function this: [object Window] (or global object in Node.js)
arrowFunction(); // Arrow function this: [object Window] (or global object in Node.js)
obj.regular(); // Regular function this: { regular: [Function: regularFunction], arrow: [Function: arrowFunction] }
obj.arrow(); // Arrow function this: { regular: [Function: regularFunction], arrow: [Function: arrowFunction] }
Output:
Regular function this: Window {window: Window, self: Window, document: document, name: '', location: Location,…}
Arrow function this: Window {window: Window, self: Window, document: document, name: '', location: Location,…}
Regular function this: {regular: ƒ, arrow: ƒ}
Arrow function this: Window {window: Window, self: Window, document: document, name: '', location: Location,…}
When function don't refer to objects
There is no diffrence when don't refer to objects