Discussion on this keyword in Javascript

In javascript, this keyword behaves differently compared to other languages. This keyword refers to an object and the manner in which it is called will be responsible for telling which object.

Mini Question:

What will be the output if we console.log this keyword globally?

Code:

console.log(this);

Output:

[object Window]

As you can see in the output window “this” keyword will refer to the window object globally.

Interview Question:

Guess the output of the following code:

Code:

function isworking(){

let firstName="Pulkit";

let lastName="Govrani";

console.log("Details of person: "+this.firstName+" "+this.lastName);

}

isworking();

Output:

Details of person: undefined undefined

Let’s take one more example where this keyword is called with an object.

Code:

const person = {
    firstName: "Pulkit", lastName : "Govrani", id : 039,
    getThis : function() {
        return "Details of person: "+this.firstName+" "+this.lastName;
    }
};
console.log(person.getThis());

Output:

Details of person: Pulkit Govrani

If we look at the above code, we are creating an anonymous function where this keyword is used to access the properties of the object person.

Therefore this can be used to access any other methods or properties while it is used inside an anonymous function.

In the case of arrow functions this behaves differently, If we take the same example and just use the arrow function instead of the anonymous function then let’s see the output.

Code:

const person = {
    firstName: "Pulkit", lastName : "Govrani", id : 039,
    getThis : () => {
        return "Details of person: "+this.firstName+" "+this.lastName;
    }
};
console.log(person.getThis());

Output:

Details of person: undefined undefined

Now here this is referring to the parent object of the person object and globally there is no firstName or lastName which is defined.

Using this in an Event Listener

If we use this keyword inside an event listener then it will simply point to the DOM element responsible for initializing the event. Let’s take an example where we are changing the text of the DOM element which triggered the event using this keyword.

HTML Code:

<button id="testBtn">Hello, This is a Testing Button</button>

JS Code:

document.getElementById('testBtn').addEventListener('click', function() {
    this.innerHTML="Text is changed using this keyword";
})

I tried to keep this blog short and sweet by mentioning only important points about this keyword in javascript. Feel free to ask your doubts below or type your thoughts in the comment box.