Understanding 'this' in JavaScript

Published: (May 13, 2026 at 05:45 PM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Overview

One JavaScript concept that confuses many developers is the behavior of this. While it may seem simple at first glance, the value of this changes depending on how a function is invoked.

Normal Functions

In a regular function, this refers to the global object (window in browsers) or is undefined in strict mode.

function test() {
  console.log(this);
}
  • Non‑strict mode: logs window (or the global object).
  • Strict mode: logs undefined.

Object Methods

When a function is called as a method of an object, this points to that object.

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

user.Name(); // Output: Swarnali

Here, the object (user) before the dot (.) becomes the value of this inside Name, allowing access to user.name. If the method is detached from its object and called independently, it loses this binding and this no longer refers to the original object.

Arrow Functions

Arrow functions do not create their own this context. Instead, they inherit this from the surrounding lexical scope where they are defined.

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

user.Name(); // Output: undefined

Because the arrow function captures this from the outer scope (which is typically the global object or undefined in strict mode), this.name does not refer to user.name. Consequently, arrow functions are generally unsuitable as object methods when you need to access the object’s own properties via this.

Choosing Between Normal Functions and Arrow Functions

A simple rule of thumb: Ask yourself, “Do I need my own this?”

  • Use a normal function when you require a distinct this value (common for object methods, class methods, and constructors).
  • Use an arrow function when you want to inherit this from the surrounding scope. Arrow functions shine in callbacks, nested functions, array methods like map() or filter(), and asynchronous operations such as setTimeout(), where preserving the parent context is important.

Conclusion

Understanding when and how this is bound helps avoid common pitfalls in JavaScript. By selecting the appropriate function type based on the need for a dedicated this context, you can write clearer and more predictable code.

0 views
Back to Blog

Related posts

Read more »

JavaScript Variables

!Article Imagehttps://media2.dev.to/dynamic/image/width=800,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuplo...

Self Introduction - The beginning

Introduction After a long time hesitating, I’ve finally decided to start learning programming from scratch — and this time, I’m going all in. Like many others,...