Understanding 'this' keyword in JavaScript

Learn how the `this` keyword works in JavaScript
Feature Image

If you belong to a programming background, you might have come across “this” keyword, multiple times. Every programming language that exists usually contains the concept of “this”, especially the modern programming languages.

But the catch here is, different programming languages have slight changes in the definitions for the “this” keyword. In this guide, I’ll explain to you “this” keyword of JavaScript.

In programming, there are some concepts that require thorough understanding before their implementation. “this” keyword is one of them. You can’t directly jump on the implementation of “this” keyword, you have to understand its properties and use cases in the first place.

Besides this, the “this” keyword is mostly used with the functions, therefore let’s learn about that in the first place.

Note: In this content, there won’t be a standard definition of “this” keyword, it is because the functionality of the keyword keeps on changing with its use case. So, it’s better for each of its use cases.


“this” Keyword When Used Alone

If you want to use the “this” keyword alone, i.e., without any function or object. In that case, the default object of the browser i.e., “window” will come into play and its value will be set to “this” keyword’s value.

For instance,

<!DOCTYPE html>
<html>
    <body>
        <script>
        document.write(this);
        </script>
    </body>
</html>

Output:

[object Window]

“this” Keyword with Functions

Usually, functions are quite easy to understand and have the most straightforward functionality. But, in JavaScript, Functions are much more complex than they seem.

JS functions are like objects. Functions also have properties. One such property is the “this” keyword. The value of the “this” keyword completely varies on how the function is invoked.

Note: “this” keyword always holds a single object value.

Different Ways of Function Invocations

  1. Basic Function Invocation
  2. Method Invocation
  3. Constructor Invocation

1. How does the “this” keyword work with Basic Function Invocation?

Before diving into some script, let me quickly brief you about Basic Function Invocation. Whenever a function is created with a body included in the opening and closing brackets and it is invoked using its name, this refers to a basic function invocation.

In such scenarios, the “this” keyword holds the value of the global object i.e the window object if the scripts are being executed in a browser environment. Therefore, any modification done on “this” keyword will be reflected in the window object.

For instance,

<!DOCTYPE html>
<html>
<body>
    <script>
    function disp(){
        this.value = "Demo Object";
    }
    
    disp();
    document.write(window.value);
    </script>
</body>
</html>

Output:

Demo Object

In the above script, instead of window.value, this.value can also be used or to understand the link between “this” and “window”, you can use the following expression:

document.write(this);

The above behaviour of the “this” keyword is valid only when the script is not using a strict mode. In the case of strict mode, the value of the “this” keyword is set to undefined.

<!DOCTYPE html>
<html>
<body>
    <script>
    function disp(){
        'use strict';
        this.value = "Demo Object";
    }
    
    disp();
    document.write(window.value);
    </script>
</body>
</html>

Here some of you might get a blank output whereas some of your might get undefined, it completely depends on the browser.

2. How does the “this” keyword work with Method Invocation?

Functions are termed methods when defined as a property of an object. So, don’t get confused with functions or methods in JavaScript.

Most developers get confused about the terminologies used. In order to make the understanding process smooth, I’m going through the whole concept in easy language using general terms.

In the method invocation process, a function is defined as a property of an object. Now, In order to invoke the function, the name of the object followed by the function name with opening and closed parenthesis is used.

For instance,

object.fuctionname();

In technical terms, the expression is known as property accessors.

In this process, the value that the “this” keyword holds is the value of the object used to invoke the method.

For better understanding, refer to the script:

<!DOCTYPE html>
<html>
<body>
    <script>
    const programming = {
        language: "JavaScript",
        level: "easy",
        display: function(){
            document.write("This is "+ this.language+" and it is quite "+ this.level+" to write code. ");
        }
    };
    
    programming.display();
    </script>
</body>
</html>

Output:

This is JavaScript and it is quite easy to write code.

Note: If you came across a script where nested functions are defined along with the “this” keyword in both the functions, you must remember that the first function “this” keyword will have the object’s value whereas the nested function “this” keyword will have the global object’s value i.e., of the “window”.

3. How does the “this” keyword work with Constructor Invocation?

Before talking about the “this” keyword in the constructor invocation, let me quickly brief you about constructor invocation.

When a function object is created using the new keyword, the function is used as a constructor. This whole concept is termed constructor invocation.

This is one of the several ways to create an instance in JS.

For instance,

let demObj = new functionName();

In this process, the “this” keyword holds the value of the newly created object.

In this process, an object is created of the function name, therefore it sets the constructor properties to the functions. Later the function is attached with the object so that it inherits all the properties of the functions or constructor function.

The constructor function then now acts as a property of the object. After the invocation, “this” keywords get access to the values that the object holds.

For instance,

<!DOCTYPE html>
<html>
<body>
  <script>
    let demoObj = function(arg1, arg2){
        this.val1 = arg1;
        this.val2 = arg2;
        
        this.disp = function(){
        document.write("This is "+ this.val1 + " and its quite " + this.val2);
        }
    }
    
    let object1 = new demoObj("JS","easy");
    
    // logs the output
    object1.disp();
    </script>
</body>
</html>

Output:

This is JS and its quite easy

Here, an object object1 is created which invokes the constructor functions. That constructor function then set’s the value of “this” keyword. Once all the properties of the object are inherited by the “this” keyword, disp() function is created that gives the desired output. It’s not that complicated, first an object is created, then a constructor function is invoked to set the values of that object and later all the values of the object are inherited by the “this” keyword.


Final Notes

You might come across some more use cases of “this” keyword that aren’t listed in this guide. It is because those use cases aren’t popular enough or not implemented extensively by the developers. Besides this, you can learn about those concepts quite easily if you have understood the above mentioned use cases.

If you come across something that is confusing, you can drop it down. We will discuss it further. Perhaps, you need to practice these scripts to get a clear picture of the “this” keyword.

Note: JS might seem quite complex while reading the scripts, but let me tell you that if you cover the basics thoroughly, you just have to be familiar with the syntax and writing style.

Thanks for reading!

Programming Web Development JavaScript TypeScript NodeJS