Skip to main content

Command Palette

Search for a command to run...

Understanding the this Keyword

in JavaScript

Updated
โ€ข3 min readโ€ขView as Markdown
Understanding the this Keyword
S
A software engineer who work across the Full Stack. Having adept skills on coding and product management

What this represents

The this keyword in JavaScript is a reference to an object, and its value is determined by the context in which a function is executed, not where it is defined.

It's value is determined by in which environment we are dealing with.

this is context-dependent.

this in global context

If you print this

console.log(this);

In return you will get an empty {} object which is typically refers to the object that is currently executing the code


If on browser then => window

If on NodeJS then => Global Object

๐Ÿ’ก
this is context-dependent. Remember!

this inside objects

When this is used inside an object's method, it refers to the object itself.

const anime = {
    name: "Spy x Family",
    getAnime(){
        console.log(this.name);
    }
}
anime.getAnime()

this inside functions

this in inside functions have several values.

If we console the type of this in a function

Output will be an object

function anime() {
   // non strict mode
   console.log(typeof this);
}
anime()

How calling context changes this

However, If we same do this on Browser this content will be changed. As we know it's value is defined in which environment we are talking about

In strict mode:

In strict mode ('use strict'), this inside a function will be undefined if it is not bound to any object.


Conclusion

Understanding this is essential for writing predictable JavaScript. In short:

  • this is a reference to an object that is determined by how a function is called (the call site), not where it is defined.

  • In the global scope it typically refers to the global object (window in browsers, global in Node.js), though strict mode and certain environments can change that.

  • Inside an object method, this normally refers to that object (the receiver).

  • In regular functions, this depends on the call: it can be the global object, undefined (in strict mode), or whatever object was used to call the function.

  • Arrow functions do not have their own this; they inherit this lexically from the surrounding scope.

Best practices:

  • Prefer explicit binding or arrow functions for callbacks where the intended this should be preserved.

  • Use strict mode to avoid accidental this being the global object.

  • Test and be deliberate about how functions are invoked to avoid surprising this behavior.

Keeping these rules in mind will help you reason about and control this across different contexts.

You are all set!

written by theadroitdev(Shivam Verma) :)

๐ŸŒ โ†’ https:/theadroitdev.com/

X โ†’ https://x.com/theadroitdev

Github โ†’ https://github.com/TheAdroitDev

ChaiCode Repo โ†’ https://github.com/TheAdroitDev/ChaiCode-Cohort-2026