“this” keyword in JavaScript

Most of us will be confused with this keyword in javascript because this in JS is different compared to this in other Programming language (JAVA) .


For All Regular function, this points to the WINDOW Object ( Global Context ) .

For Instance,

Output :

You can see that when it is a Regular functional call wherever it is present it refers to the Global Object ( Window in browsers ).

User.sayHello() => is a Object call so this refers to the User Object.

Let Us See Some other Examples

In this case, we need to iterate through the all the elements in array students and map it to the in-charge as I said earlier regular function “this” refers to Global Context and we have no in charge declared in the Global Context so it remains undefined

So this is something confusing in JavaScript to overcome we cand do 2 thing

  1. Bind this keyword

2 . we can use ES 6 Arrow function , where “this” doesn’t refer to its own context ,but use the this of the surrounding lexical context