DEV Community

Cover image for What the hell is 'this' in javascript?
hariszulfiqar054
hariszulfiqar054

Posted on

What the hell is 'this' in javascript?

JavaScript, with its reputation for complexity, often leaves developers scratching their heads. Today, let's tackle one of its puzzling aspects – the notorious this keyword. Despite being vital, it tends to confuse even seasoned developers. Fear not, as we're about to unravel the mystery and make sense of what the heck this is all about in JavaScript.

Enough talk let's see how it works with some coding examples:

Image description

Hmm so what will be the output of this code 🤔
The answer is pretty simple the output will be a global object, but this pops another question that what is global object?

The value of global object depends on the environment where the javascript code will run, for example if this code runs on the browser the global object value will be window object and if this code runs in nodejs the value will be different and vice versa this type of behavior is called default binding of this.

let's take a look on few more examples to understand it more.

Image description

Take a moment and think what will be the value of this?
Yes you got it right the value will be a global object. But there is another mystery in this code example, what if we execute this code example in a strict mode of javascript?
Note: To read more about strict and non-strict mode
The output of this will be undefined but why the value of this is a global object in non-strict mode? The answer is pretty simple it's because of the this substitution in javascript which happens during the run-time.

Let's unfold how this works inside the methods.
FYI : Methods are the function which are associated with an object.

Image description

let's execute the code see the output.

Image description

As you can see the value of this is referring to it's parent object because the execution context is changed from global object to a javascript object this process is called implicit binding.

What if we replace the printName function with an arrow function?

Image description

In this case the output of this will be a global object as in arrow function javascript refers the value of this from the enclosing lexical context in this case the enclosing lexical context is global object. Let's take another example to clear the doubts about it.

Image description

As we know that in case of arrow functions the value of this is the enclosing lexical context in this case the enclosing lexical context is the function printName so as a result the value of this will be the following.

Image description

There is also one more topic where you can explicitly change the value of this during the runtime execution using some functions for example call, bind and apply. Let's leave this for another discussion. I hope you find this article helpful. :)

That's pretty much you can read more about this here.

Top comments (0)