Skip to main content

Command Palette

Search for a command to run...

Understanding The this Keyword in JavaScript

The Most Confusing Concept Made Simple

Updated
3 min readView as Markdown
Understanding The this Keyword in JavaScript

Introduction

The this keyword in JavaScript confuses almost everyone at first.

But here's the simplest way to think about it:

this refers to who is calling the function

Not where it's written, but how it's called.

What Does this Represent?

this is a special keyword that refers to the execution context (caller) of a function.

In simple terms:

  • It points to the object that is calling the function.

this in Global Context

In browser:

console.log(this);

Output:

window

So, in the global scope:

  • this --> window object (in browsers)

this Inside Objects

When a function is inside an Object:

this refers to the object itself

Example:

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

user.greet(); // Tony

Why?

  • user is calling greet()

  • So this = user

this Inside Functions

Here's where things get tricky

Regular Function (Non Strict Mode)

function show() {
  console.log(this);
}

show();

Output

  • window (in browser)

In Strict Mode

"use strict";

function show() {
  console.log(this);
}

show();

Output

  • undefined

How Calling Context Changes this

This is the most important rule

this depends on HOW a function is called.

Example 1: Method Call

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

user.greet(); // Tony

Example 2: Function Call

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

const fn = user.greet;
fn(); // undefined or window.name

Why?

  • Function is called independently

  • No object --> this changes

Key Rule To Remember

  • Don't ask: Where is the function defined?

  • Ask: How is the function called?

Common Mistakes

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

user.greet(); // ❌ undefined

Arrow function do not have their own this

Everyday Analogy

Phone Call Example

  • You received call

  • Who is speaking depends on who called you

Same with this

  • It depends on who is calling the function

Suggestion For Leaning

1. Always Check the Caller

Find who is calling the function --> that's your this

2. Use Simple Object Example

Avoid complex nested scenarios initially

3. Avoid arrow function for Methods

Use normal function inside objects

4. Practice Context Switching

Assign functions to variables and observe changes

Quick Summary

Scenario Value of this
Global Scope window (browser)
Object methods That object
Regular function window/undefined
Arrow function Inherited this

Final Thoughts

  • this = caller of the function

  • It changes based on how the function is called

  • Mastering it makes you a better JavaScript developer

Understanding The this Keyword in JavaScript