What is difference between this keyword inside an arrow function vs. a regular function in JavaScript?🤔

Published Date March 02, 2023

blog_image

What is difference between this inside an arrow function vs. a regular function in JavaScript🤔

JavaScript provides two ways to declare functions: using the function keyword and using arrow functions (=>). While both can be used to achieve the same result, there is a difference in how they handle the this keyword.

In a regular function declared using the function keyword, the value of this inside the function is determined by how the function is called. If the function is called as a method of an object, this refers to the object. However, if the function is called without any context (i.e., just as a standalone function), this refers to the global object (window in a browser or global in Node.js).

On the other hand, with arrow functions, this is determined by the surrounding context (the "lexical scope") when the function is defined. This means that this inside an arrow function will always refer to the same value, regardless of how or where the function is called.

For example, consider the following code:

const obj = { name: "John", greet: function() { console.log(`Hello, my name is ${this.name}.`); } }; obj.greet(); // Output: "Hello, my name is John." const greetFunction = obj.greet; greetFunction(); // Output: "Hello, my name is undefined."

In the second call to greetFunction(), this inside the function refers to the global object, so this.name is undefined.

In contrast, an arrow function would behave differently in this case:

const obj = { name: "John", greet: () => { console.log(`Hello, my name is ${this.name}.`); } }; obj.greet(); // Output: "Hello, my name is undefined." const greetFunction = obj.greet; greetFunction(); // Output: "Hello, my name is undefined."

In this case, this inside the arrow function always refers to the global object, so this.name is undefined in both calls.

In summary, the main difference between this inside a regular function and an arrow function is that the former depends on how the function is called, while the latter depends on where the function is defined. It's important to keep this in mind when deciding which type of function to use in a particular situation.