Skip to main content

Command Palette

Search for a command to run...

Understanding this in Javascript

Updated
5 min read
Understanding this in Javascript

Hello readers,

Welcome to another blog. Until now, I have covered all the basics of JavaScript, and thank you so much for appreciating my effort.

In this blog, I'm going to cover the most important and confusing topic of JavaScript, which is "this." It is the most confusing topic of JavaScript, but after reading this blog, you will have a clear understanding of this and its behavior.

Let's understand this with a Bollywood example.

Imagine Ranveer Singh (yup, our Dhurandhar)

He is an actor, and his real name is Ranveer Singh, but something interesting happens in movies.

In one movie, he is Bajirao.

In one movie, he is Alauddin Khilji.

In another movie, he is Hamza.

The actor is the same, but his identity changes depending on the movie he is acting in.

In JavaScript, functions behave exactly like actors.

And the movie they are acting in determines who they represent at that moment.

That changing identity is exactly what this it is.

this represents the object that is calling the function. It gives context to the functions or class.

So think of it like this:

Actor (Function) → Ranveer Singh
Movie (Object) → Bajirao Mastani / Gully Boy
Role (this) → Bajirao / Hamza

this inside Objects

this Inside an object means Ranveer works in a movie, and this value will change according to that movie.

Example:

const bajiraoMovie = {
  heroName: "Bajirao",
  actor: "Ranveer Singh",
  introduce() {
    console.log("I am", this.heroName);
  }
};

bajiraoMovie.introduce(); // I am Bajirao

//another movie
const gullyBoyMovie = {
  heroName: "Murad",
  actor: "Ranveer Singh",
  introduce() {
    console.log("I am", this.heroName);
  }
};

gullyBoyMovie.introduce(); //I am Murad

Here, you can see the movie changes the value of this change, but the function (introduce) is the same.

This is how this it works in JavaScript.

This doesn't depend on where the function is written, it depends on who is calling the function.

this inside the Global Context

console.log(this);

In this code blog, this is not called inside any object or function, so what do you think should be the output?

This output also depends on the environment where JS is running, because JS runs in different environments like browsers, mobile, desktops, etc.

So, the this keyword returns a Global Object whose value completely depends on the environment.

For a browser: the Global Object is equal to window, so you will get window as output.

For a Node environment, the Global Object is equal to global, so you will get global as output.

💡
This happens because the global environment becomes the caller.

Example:

function x(){
    console.log(this)
}
window.x(); //output - window (becuase window is calling)

Just like this, you can imagine the above code snippet.

this Keywords also behave differently in strict and non-strict mode

There are two modes in JS: strict and non-strict.

console.log(this)

So, if you run the above snippet in strict mode, then you will get undefined, but the same code will give window as output in non-strict mode.

The reason is this Substitution

this Substitution:

If the value of this is undefined or null, then this keyword will be replaced with the Global Object. This only works in non-strict mode.

this inside normal functions

 function introduce() {
  console.log("Hello, I'm",  this.name);
}

let user1 = { name: "abhishek", introduce };
let user2 = { name: "agam", introduce };

user1.introduce(); // Hello, I'm abhishek
user2.introduce(); // Hello, I'm agam

The above code snippet explains that inside the function, this behaves according to the caller; it doesn't depend on where it is written. The output varies based on which user is calling the introduce function.

this Inside Arrow Functions

const introduce = () => {
  console.log("Hello, I'm", this.name);
};

let user1 = { name: "abhishek", introduce };
let user2 = { name: "agam", introduce };

user1.introduce(); // Hello, i'm undefined
user2.introduce(); // Hello, i'm undefined

Arrow functions don't have their own this. Arrow functions take this value from their lexical environment where they exist. That's why here we are getting undefined because introduce is in global and in global this.name value is undefined.

What is the lexical environment?

In simpler words:

Lexical Environment means where the function is written. That's it.

In the above example Introduce is written in the global, and the global value of this in the browser is Windows.

console.log(this) // output window (in global)
console.log(this.name) // it equal to window.name = undefined

another example of an arrow function, but in a different lexical environment

let user = {
  name: "abhishek",
  greet() {
    setTimeout(() => {
      console.log(this.name);
    }, 1000);
  }
};

user.greet(); // abhishek

In the above example, the arrow function is written inside the greet() function, so the lexical environment of the arrow function is the greet() function. Since greet() is a normal function, it has access to the name value, which is why we get the output "abhishek."

That's it about this the keyword. I hope this blog helps you to clear your doubts related to this keywords in JavaScript. Here is the final mental model

in normal function = who is calling me that is this
in arrow function = what was i created decides this
in global this value depends on environment. 

Now you know that "this" provides context, but did you know you can change it? Yes, you can alter the context and even borrow functions from other objects. Sounds intriguing, right? My next blog will dive into this topic (call, apply, and bind). Until then, see you soon. Keep reading and exploring. Peace.

JavaScript this Explained with Real Examples