JavaScript

What is the “this” Keyword in JavaScript?

If you have programmed in Java, C++, or any other language you must be familiar with the “this” keyword. However, in JavaScript, it works a little differently. It is different because JavaScript offers a strict mode. Strict mode is where we cannot use undeclared variables. Strict mode also helps in debugging.

The keyword “this” is widely used in almost every programming language. However, it is also the most confusing concept. If you are a beginner don’t worry, today we will cover almost everything about the “this” keyword in JavaScript along with examples. So sit tight, and let the ride begin.

What is “this” keyword

The simplest definition of the “this” keyword is that it points to or refers to an object to which it belongs. We can also say that it references that object which is calling the function/method currently.

Now that we know what the “this” keyword means, let us discover where it is used. The value of the “this” keyword also differs based on where it is used.

Using “this” keyword alone

The keyword “this” can be used alone without any method. However, it then holds the reference to the global object. For Example:

const xyz=this;
alert(xyz);

In this example, we initialized a variable, which stores the reference to the global object. It should be kept in mind that the browser window global object is [object window]. When we run the following code, we will get the following alert:

We can also use the “this” keyword alone using strict mode. The solution will be the same i-e it will show the [object Window] alert. The code will look like this:

const xyz=this;
alert(xyz);

Using “this” keyword in Function

Using the “this” keyword in a function is the default way. “this” keyword will also refer to the global object in a function. For Example:

function myFunc(){
    alert(this);
}
myFunc();

However, if we use this keyword in strict mode then the result is undefined. It is because in strict mode JavaScript restricts default binding. For Example:

use strict";
function myFunc(){
    alert(this);
}
myFunc();

In this example, we used “use strict”. We will be returned undefined when we run this code.

Using “this” keyword in Event handlers

Event handlers handle events. For example, if you click a button, that click will be handled by event handlers. If we want to refer to that button element in HTML from which we received the click then we use the “this” keyword.
For example, suppose we have a button. We want to make it vanish once we click it. We will achieve it by the following code:

Html:

<body>
    <button class="vanish-btn">Click me to see magic</button>
    <script src="code.js"></script>
</body>

JavaScript:

const btn= document.querySelector(".vanish-btn");

btn.addEventListener('click',function(){
    this.style.display="none";
})

In this code, in HTML we first created a button with the class name of “vanish-btn”. After that, we put the script tag where we referenced the file name of JavaScript. In the JavaScript file, we first get the reference of the button in “btn” with the help of the class name. After that, we put an event listener with the click of a button. In this whenever the button will be clicked, the callback function will run where we made the display of the button none.

Before clicking the button the browser will look like this:

When we click on the click me to see magic button it will vanish.

Object Method Binding

We will give some examples first and then we will discuss it to grasp the concept. However, keep in mind that the keyword “this” is the player object defined in the following example or the parent object which it is referencing.

const player = {
    name : "Hazard",
    club : "Chelsea",
    shirtNo : 10,
    myFunc : function() {
        return this.name;
    }
};
alert(player.myFunc()+ " plays for " + player.club);

In this example we initiated an object with the name of “player”. We specified its properties like name, club, and shirt number. After that, we made a function. In the end, we alert the player object function and the club he plays for. This is used in the myFunc() function. In this, it is referencing the player name with the keywords “this. name”. The result within an alert will look like this:

Keyword “this” in an arrow function

Arrow functions were first introduced in the ES6 version and have a similar function to a standard JavaScript function except that arrow functions shorten the syntax.
For example:

function myFunc(){
    return "Champions of Europe"
}
myFunc();

This can be written as:

const myFunc= ()=>{
    return "Champions of Europe";
}

Keyword “this” is handled differently in an arrow function than in the default function. To be precise, arrow functions have no binding of the “this” keyword. Also, the “this” keyword refers to the variable or object that defined the arrow function.
For Example:

const player =()=> ({
    name : "Hazard",
    club : "Chelsea",
    shirtNo : 10,
    myFunc : function() {
        return this.name;
    }
});
alert(player().myFunc());

Keyword “this” here referenced the player as the player-defined the arrow function.

Conclusion

In this article, we discussed what “this” keyword is and how it is used. We also discussed where and how we can use the “this” keyword. All this with the help of examples. “This” keyword is an important concept of JavaScript and mainly beginners struggle with this. We hope that this post has clarified any ambiguities you may have had.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.