Home Courses "this" Keyword Explained

"this" Keyword Explained

The this keyword is one of the most important concepts in JavaScript. It is commonly asked in interviews and used in real projects.


What is this?

this refers to the current object in which it is used.

In simple words, it points to the object that is calling the function.


Real-Life Example Idea

Think like this:

If you are in a room, and you say “this room”, you mean the current room you are in.

Same way in JavaScript, this means the current object you are working with.


Object Example

We create two objects:

  1. user object (main object)
  2. address object (extra details)


Code Explanation

User Object


let user = {
name: "anil",
age: 29,
moreDetails: function () {
console.log("hello, my name is " + this.name + ", my house no is " + address.houseNo);
}
}

Address Object


let address = {
houseNo: 663,
city: "gurgaon"
}


Calling Function


user.moreDetails();


Output Logic

When we call:


user.moreDetails()

What happens:

  1. this.name refers to user.name
  2. So it prints "anil"
  3. address.houseNo is accessed directly from another object


Important Concept

Inside an object method:

  1. this refers to the object that calls the function
  2. Here, this refers to user

So:


this.name → user.name


Final Output

hello, my name is anil, my house no is 663



Share this lesson: