DEV Community

Cover image for Understanding 'this' in JavaScript
Swarnali Roy
Swarnali Roy

Posted on

Understanding 'this' in JavaScript

One JavaScript concept that confused me for a long time is the concept of this. At first, it looks simple. But while using inside a function, the behavior changes based on how the function is called.

It works differently in :

  • Normal function
  • Object Method
  • Arrow Function

Normal Function

In a normal function, this usually refers to the global object or undefined in strict mode.
Example:

function test() {
  console.log(this);
}
Enter fullscreen mode Exit fullscreen mode

The output will show window in a non-strict mode and undefined in a strict mode.

Object Method

When a function is called as a method of an object, the this keyword refers to the object that is calling the method.
Example:

const user = {
  name: "Swarnali",
  Name() {
    console.log(this.name);
  }
};
user.Name();

//Output : Swarnali
Enter fullscreen mode Exit fullscreen mode

In user.Name(), the object (user) before the dot(.) becomes the value of this inside the function. That is why this.name accesses user.name. This allows methods to work with the object’s own properties dynamically. However, if the function is separated from the object and called independently, it loses that connection, and this no longer refers to the original object.

Arrow Function

Arrow functions behave differently from normal functions because they do not create their own this context. Instead, they inherit this from the surrounding scope where the arrow function was originally defined. This is called lexical scoping.
Example:

const user = {
  name: "Swarnali",
  Name: () => {
    console.log(this.name);
  }
};

user.Name();

//Output: undefined
Enter fullscreen mode Exit fullscreen mode

In this example, Name is defined using an arrow function inside the user object. As a result, this.name will not access "Swarnali" and may return undefined depending on the environment. This is why arrow functions are generally not recommended as object methods when you need to access the object’s own properties using this.

How to determine when to use which this?

One easy method to determine whether to use a normal function or an arrow function would be the question, "Do I need my own this?"
In cases where the function must access variables from the object that called it, the choice would be to write a normal function since they have their own this value. This is common for object methods and class methods.
When a function requires a this value passed to it through the surrounding scope, then write an arrow function. Arrow functions are especially useful in callbacks, nested functions, array methods like map() or filter(), and asynchronous operations such as setTimeout(), where preserving the parent context is important.

Do you face this confusion as well?

Top comments (0)