THIS Keyword In JavaScript
By Kartikey Yadav
javascript

Hey guys,

The 'this' keyword is one of the important concepts in JS and is used everywhere and so it becomes very important for us to understand "this"

But I know there is a lot of confusion regarding the "this" keyword and I did too when I was learning about it so don't worry it's ok if you don't understand it in the first go but I will try to hopefully make you understand what it is.

Let's start simple

I am assuming that you guys know what the "window" object is, because the "this" keyword is all revolving around objects and things like that so if you don't please learn about it and come back

Now when you type in your console

this === window; // true

This statement will be true,

So does that mean that the "this" keyword is just the window object and nothing else?

Well, you see the "this" keyword depends on where it is written i.e in which object it is defined.

In whichever object it is defined it will refer to that particular object

Let's understand this a little better by an example

function hello() {
console.log(this);
}
hello(); // the output will be the window object window.hello()

In the above example as you can see

We have made a function hello() and inside the function, we have console.log(this),so what do you think should be the output?

The output will be the window object, but how?

See the "this" keyword always refers to the object in which it is to be defined so the

"this" keyword is the object the function is property of"

Here as you can see the function hello is the property of the window object and if "this" is used inside the function it will refer to the window object

As a tip always remember that whatever is to the left of the method is the object the "this" keyword is referring,so here as you can see window.hello() is present so to the left of hello there is the window object and so the "this" keyword is referring to the window object

Let's see another example

const singer = {
name: "Joy",
sing() {
return "ullaa " + this.name;
},
};
singer.sing(); // ullaa Joy

By seeing this example I hope you might have understood it a little better

In this example here, we have made an object name "singer"

The object singer has two properties name and sing, we have used the "this" keyword in the sing method

Now if you remember from the previous example, the function was defined in the window object but here the function sing is defined inside the singer object so it's obvious that the "this" keyword is referring to the singer object

Here too you can apply our tip of seeing the left side of the method, which in this case is the singer object and it's what the "this" keyword is referring to.

Here is another example for you to understand better

const singer = {
name: "Joy",
sing() {
return "ullaa " + this.name;
},
singAgain() {
return this.sing() + "hahaha";
},
};
singer.sing(); // ullaa Joy
singer.singAgain(); // ulla Joy hahaha

Here as you can see it is the extension of the previous example

As you can see that we have referred to the sing function from the singAgain function using the this keyword, so instead of writing the whole function again I have just used the this keyword to refer to that piece of code and that helps in writing DRY code

The two main important benefits of using the "this" keyword are

  1. Giving methods access to their objects
  2. Executing the same code for the multiple objects

We have understood the first part in the above examples where we saw that the singAgain and sing function had access to their object

Now, Let's see the second part

Example

function getHelper() {
console.log(this.name);
}
const name = "Jasprit";
const worker = {
name: "Jessica",
helper: helper,
};
const worker1 = {
name: "Jason",
helper: helper,
};
getHelper(); //Jasprit
worker.getHelper(); //Jessica
worker1.getHelper(); //Jason

As you can see from the above code, we have made a reusable function getHelper which returns the helper from the object on which it is called

In the object named worker, the "this" keyword defined in the getHelper function is referring to the name Jessica and in worker1 it's referring to Jason and in the global object its referring to the global variable name - Jasprit

Now we can see that this keyword is helping us write better code

Some Important concepts regarding this keyword

For understand the first concept we need to a little bit about the lexical and dynamic scope,

I have covered these concept in details in our other blog but just for recap here it is in brief

In JS our lexical scope ( available data + variables where the function is defined) determines our available variables not where the function is called which is called dynamic scope

What I mean here is, in JS we have lexical scope which means the available data and variable are defined where the function is defined and it doesn't matter where the function is called , but in dynamic scope it does matter where the function is called

If you want to know more about the lexical scope check out this blog here

But there is an exception to this rule which is that the "this" keyword doesn't follow it

Let's see how

const singer = {
name: "Joy",
sing() {
console.log("1", this);
var singAgain = function () {
console.log("2", this);
};
singAgain();
},
};
singer.sing();

Now what do you think will be the outcome of the first and the second console.log( )

OK let's check it out

The output of the first console.log( ) is "singer" but the output of the second console.log( ) is the "window" object which is weird

As you can see function singAgain( ) is called inside the sing( ) function, it is not called inside the object "singer" it is called inside the sing() function, and by default, the "this" keyword is the window object

Now if you remember I wrote a statement above and said that the "this" keyword is an exception to this rule which means that the " this" keyword is dynamically scoped and it doesn't matter where it is written but where the function is called and because of this property of this keyword that we have such behaviour

But there are ways to tackle this problem

  1. Using arrow function
  2. Declaring "this" keyword at the start and using the substitute in place of "this"
  3. Using bind

Let's see each one by one

1.Using arrow function which are lexically bound and what that means is in ES6 we can use the arrow function to bind the "this" keyword to that specific object

Using the previous example

const singer = {
name: "Joy",
sing() {
console.log("1", this);
var singAgain = () => {
console.log("2", this);
};
singAgain();
},
};
singer.sing();

Here the first and the second console.log( ) will have the same value which is equal to the object "singer"

2.Redefining the this keyword

const singer = {
name: "Joy",
sing() {
console.log("1", this);
var self = this;
var singAgain = function () {
console.log("2", self);
};
singAgain();
},
};
singer.sing();

As you can see from the above example we have stored the value of the "this" keyword inside the variable self when it was still referring to the singer object and used the declared variable self instead of the "this" keyword inside the singAgain function and it solves the issue kind of like Juggad

3.Using the Bind method

const singer = {
name: "Joy",
sing() {
console.log("1", this);
var singAgain = function () {
console.log("2", this);
};
return singAgain.bind(this);
},
};
singer.sing()();

The bind method, you read about it here for more info, but here we are just binding the "this" keyword to the object "singer" and returning the function, also notice that we have to call singer.sing()() twice because then only it will return the second function

So these were a few important concepts related to the "this" keyword, if you think that I might have missed something than please let us know and we will add it right away

I hope you understood the main concept of the "this" keyword and what it is, always remember the line

"this" keyword is the object that the function is the property of"

Was the article helpful? Do you have any doubts? Any topic you would like us to cover?

Reach out to us on Twitter and Instagram where we try to provide more value in threads and carousal formats

Thank You for your time

Keep learning, Keep coding :)