Chapter 25 of 49

JavaScript this Keyword

In the Objects chapter, we wrote methods like this:

const user = {
    name: "Riya",
    greet() {
        console.log("Hi, I am " + this.name);
    }
};

user.greet();

Output:

Hi, I am Riya

Here this clearly means user. But this in JavaScript doesn't always behave so nicely. The same function can see a different this depending on how it's called, and that confuses beginners and experienced developers alike.

In this chapter, we'll learn the small set of rules that decide what this is, so you can predict it every time.

What is this?

this is a special keyword that refers to the object a function is working with. For regular functions, its value is decided when the function is called, based on how it is called, not where it is written.

That last part is the key idea. In most languages, this is fixed to an object. In JavaScript, a regular function gets its this fresh on every call. Arrow functions are the exception; we'll see them later in this chapter.

Here are all the rules we'll cover:

How the function is called

What this is

As a method: obj.method()

obj (the object before the dot)

As a plain function: fn()

undefined in strict mode, the global object otherwise

With call, apply or bind

Whatever object you pass in

With new: new Fn()

The brand-new object being created

Arrow function

No own this; uses this from the surrounding code


Rule 1: Method Calls (Look Left of the Dot)

When a function is called as object.method(), this is the object to the left of the dot.

The function doesn't "belong" to an object. The same function can be shared by many objects, and this changes with each call:

function introduce() {
    console.log("I am " + this.name);
}

const aman = { name: "Aman", introduce };
const sara = { name: "Sara", introduce };

aman.introduce();
sara.introduce();

Output:

I am Aman
I am Sara

It's the same introduce function both times. The only difference is what's left of the dot at the moment of the call.

This also works with nested objects. Only the object immediately before the method counts:

const college = {
    name: "City College",
    department: {
        name: "Computer Science",
        show() {
            console.log(this.name);
        }
    }
};

college.department.show();

Output:

Computer Science

Because show() was called on college.department, this is college.department, not college.

A nice use of this rule is method chaining: if a method returns this, you can call another method right after it.

const counter = {
    count: 0,
    increment() {
        this.count++;
        return this; // return the object itself
    }
};

counter.increment().increment().increment();

console.log(counter.count);

Output:

3

Rule 2: Plain Function Calls

When a regular function is called on its own, with nothing to the left of a dot, there's no object for this to point to. What happens depends on strict mode.

Strict mode is a safer version of JavaScript that you turn on by writing "use strict"; at the top of a file or function. JavaScript modules and classes are always in strict mode automatically.

"use strict";

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

showThis();

Output:

undefined

Without strict mode (old "sloppy" mode), this in a plain function call falls back to the global object (window in browsers, globalThis in general):

function showThis() {
    console.log(this === globalThis);
}

showThis();

Output:

true

Strict mode's undefined is better: if you use this by mistake, you get a clear error instead of silently reading or creating global variables.


Losing this

Rules 1 and 2 together explain the most common this bug. Watch what happens when we take a method out of its object:

"use strict";

const user = {
    name: "Riya",
    greet() {
        console.log("Hi, I am " + this.name);
    }
};

const greet = user.greet; // copy the function, no call yet

// try...catch catches the error so we can print it and keep going (covered in the Error Handling chapter)
try {
    greet(); // plain function call → this is undefined
} catch (error) {
    console.log(error.name + ": " + error.message);
}

Output:

TypeError: Cannot read properties of undefined (reading 'name')

(That is the Chrome/Node.js wording. Without strict mode, there'd be no error, but this would be the global object and you'd get the wrong name.)

greet is the very same function as user.greet, but it was called without user. in front, so Rule 2 applies.

The same thing happens, less obviously, when you pass a method as a callback:

"use strict";

const user = {
    name: "Riya",
    greet() {
        console.log("Hi, I am " + this.name);
    }
};

function runLater(callback) {
    callback(); // called as a plain function!
}

try {
    runLater(user.greet);
} catch (error) {
    console.log(error.message);
}

// Fix: wrap it, so greet is still called as a method
runLater(() => user.greet());

Output:

Cannot read properties of undefined (reading 'name')
Hi, I am Riya

Passing user.greet hands over only the function. The connection to user is lost. This is exactly what happens with setTimeout(user.greet, 1000) or button.addEventListener("click", user.greet): those APIs call your function in their own way, not as user.greet().

Wrapping the call in an arrow function is one fix. The other is bind(), coming up next.


Rule 3: call, apply and bind

Functions in JavaScript come with three built-in methods that let you decide what this should be. This is called explicit binding.

function introduce(city, country) {
    console.log(this.name + " from " + city + ", " + country);
}

const person = { name: "Aman" };

// call: arguments passed one by one
introduce.call(person, "Delhi", "India");

// apply: arguments passed as an array
introduce.apply(person, ["Mumbai", "India"]);

// bind: returns a NEW function with this fixed (and optionally some arguments)
const introduceAman = introduce.bind(person, "Pune");
introduceAman("India");

Output:

Aman from Delhi, India
Aman from Mumbai, India
Aman from Pune, India

Method

Calls the function immediately?

How arguments are passed

fn.call(obj, a, b)

Yes

One by one

fn.apply(obj, [a, b])

Yes

As an array

fn.bind(obj, a)

No, returns a new function

One by one (pre-filled), rest later

A simple memory trick: call = commas, apply = array.

Fixing Lost this with bind

"use strict";

const user = {
    name: "Riya",
    greet() {
        console.log("Hi, I am " + this.name);
    }
};

function runLater(callback) {
    callback();
}

const boundGreet = user.greet.bind(user);

runLater(boundGreet);

Output:

Hi, I am Riya

A bound function has its this locked permanently. Even call() or another bind() can't change it:

function showName() {
    console.log(this.name);
}

const bound = showName.bind({ name: "First" });

bound();
bound.call({ name: "Second" });
bound.bind({ name: "Third" })();

Output:

First
First
First

Rule 4: Arrow Functions Have No Own this

As mentioned in the Arrow Functions chapter, arrow functions don't create their own this. Inside an arrow function, this is simply whatever this was in the code surrounding the arrow function, where it was written. This is called lexical this, the same "decided by where it's written" idea we saw with closures.

This also means call, apply and bind cannot change an arrow function's this.

Where Arrow Functions Help: Callbacks Inside Methods

const team = {
    teamName: "Team India",
    players: ["Rohit", "Virat"],

    showWithRegular() {
        this.players.forEach(function (player) {
            // regular function called by forEach as a plain function
            console.log(player + " plays for " + this.teamName);
        });
    },

    showWithArrow() {
        this.players.forEach(player => {
            // arrow function uses showWithArrow's this → team
            console.log(player + " plays for " + this.teamName);
        });
    }
};

team.showWithRegular();
team.showWithArrow();

Output:

Rohit plays for undefined
Virat plays for undefined
Rohit plays for Team India
Virat plays for Team India

In showWithRegular(), the inner regular function is called by forEach() as a plain function, so it gets its own this (the global object here; in strict mode it would be undefined and throw an error). In showWithArrow(), the arrow function has no this of its own, so it uses the this of showWithArrow(), which is team.

Before arrow functions, developers wrote const self = this; in the method and used self inside the callback. Arrow functions made that trick unnecessary.

Where Arrow Functions Hurt: As Object Methods

Because arrow functions don't get this from the object, they make poor object methods:

const user = {
    username: "Riya",

    regularMethod() {
        console.log(this.username);
    },

    arrowMethod: () => {
        console.log(this.username);
    }
};

user.regularMethod();
user.arrowMethod();

Output:

Riya
undefined

An object literal { } does not create a new scope for this. So arrowMethod uses the this of the code around the object, which is the top level of the file, not user. (In a JavaScript module, top-level this is undefined, so this line would even throw a TypeError.)

Use regular (shorthand) methods for object methods, and arrow functions for callbacks inside them.


Rule 5: this with new

When a regular function is called with the new keyword, JavaScript creates a brand-new empty object and sets this to it. Such functions are called constructor functions, and by convention their names start with a capital letter.

function Student(name, course) {
    // this = a new empty object
    this.name = name;
    this.course = course;
    // the new object is returned automatically
}

const s1 = new Student("Kabir", "BCA");
const s2 = new Student("Meera", "B.Tech");

console.log(s1.name + " - " + s1.course);
console.log(s2.name + " - " + s2.course);

Output:

Kabir - BCA
Meera - B.Tech

Arrow functions can't be used with new at all, because they have no this to set up. In the next chapter, we'll see that classes are the modern, cleaner way to write constructors, and the same this rules apply inside them.


this in Other Places

At the Top Level

Outside any function, this depends on the environment:

Environment

Top-level this

Browser, normal <script>

window

Any JavaScript module (type="module" or .mjs)

undefined

Node.js CommonJS file

module.exports (an empty object {} at first)

If you need the global object in any environment, use globalThis instead of relying on this.

In Event Handlers

When you attach a regular function as a DOM event handler, the browser calls it with this set to the element the handler is attached to. An arrow function handler would instead use the surrounding this. We'll see this in the DOM Events chapter; usually it's clearer to use event.currentTarget instead of this.


Which Rule Wins?

When more than one rule seems to apply, use this order (highest first):

0. Arrow function?               → use the surrounding this (nothing else matters)
1. Called with new?              → the new object
2. call / apply / bind used?     → the object passed in
3. Called as obj.method()?       → obj
4. Plain call fn()               → undefined (strict) or global object (sloppy)

To figure out this for a regular function, don't look at where the function was defined. Look at the line where it is called.


Common Mistakes

  • Passing a method as a callback (setTimeout(obj.method, 1000)) and losing this. Wrap it in an arrow function or use bind().

  • Using an arrow function as an object method and expecting this to be the object.

  • Using a regular function as a callback inside a method and expecting it to share the method's this. Use an arrow function.

  • Expecting call() or bind() to change an arrow function's this. It can't be changed.

  • Confusing call and bind. call runs the function now; bind gives you a new function to run later.


Interview Questions

Question 1: What does this print?

const obj = {
    value: 10,
    outer() {
        const inner = () => this.value;
        return inner();
    }
};

console.log(obj.outer());

Output:

10

outer() is called as a method, so its this is obj. The arrow function inner borrows that this.

Question 2: What does this print?

function getValue() {
    return this.value;
}

const a = { value: "A", getValue };
const b = { value: "B" };

console.log(a.getValue());
console.log(a.getValue.call(b));

const fixed = a.getValue.bind(a);
console.log(fixed.call(b));

Output:

A
B
A

call(b) overrides the method call, but a bound function ignores call().

Question 3: "What is the difference between call, apply and bind?" See the table above: call and apply invoke immediately (commas vs array), bind returns a new function with this permanently set.

Conclusion

For regular functions, this is decided by how the function is called. For arrow functions, it comes from the surrounding code.

  • obj.method() → this is obj.

  • fn() → undefined in strict mode, the global object otherwise.

  • call/apply/bind → this is whatever you pass; bind fixes it permanently.

  • new Fn() → this is the newly created object.

  • Arrow functions have no own this: great for callbacks, bad for object methods.

With this understood, you're ready for classes, where this is used in almost every line.