What is “this” in Javascript? | Explaining this keyword in Javascript!

What is “this” in Javascript? | Explaining this keyword in Javascript!

In this JavaScript tutorial, we will learn about what is “this” keyword in JavaScript. You'll understand this and its mechanism, in depth. The this keyword in JavaScript has often been a source of much confusion for beginners to the language.

What is “this” in JavaScript?

If you have been building things using JavaScript libraries, you might have noticed a particular keyword called this.

this is quite a common thing in JavaScript, but there are a quite a few developers who have taken quite some time to fully understand what this keyword exactly does and where should it be used in your code.

In this post I will help you understand this and its mechanism, in depth.

Before diving in, make sure you have Node installedon your system. Then, open a command terminal and run the node command.

“this” in Global Environment

The working mechanism of this is not always easy to understand. To understand how this works, we will start looking at this in different environments. Let’s start by looking at the global environment first.

At the global level, this is equivalent to a global object called global.

> this === global

But this is true only inside node. If we try to run this same code inside a JavaScript file, we will get the output as false.

To test this, create a file called index.js with the following code inside it:

console.log(this === global);

Then run this file using the node command:

$ node index.js

The reason for this is that inside a JavaScript file, this equates to module.exports and not global.

“this” inside Functions

The value of this inside a function is usually defined by the function’s call. So, this can have different values inside it for each execution of the function.

In your index.js file, write a very simple function that simply checks if this is equal to the global object.

function rajat() {
  console.log(this === global)

If we run this code using node, we will the output as true. But we add "use strict" at the top of the file and run it again, we will get a false output because now the value of this is undefined.

To further explain this, let’s create a simple function that defines a Superhero’s real name and hero name.

function Hero(heroName, realName) {
  this.realName = realName;
  this.heroName = heroName;
const superman= Hero("Superman", "Clark Kent");

Note that this function is not written in strict mode. Running this code in node will not get us the value of “Superman” and “Clark Kent” as we expected, but it will instead just give us an undefined.

The reason behind this is that since the function is not written in strict mode, this refers to the global object.

If we run this code in strict mode, we will get an error because JavaScript does not allow us to assign properties realName and heroName to undefined. This actually is a good thing because it prevents us from creating global variables.

Lastly, writing the function’s name in uppercase means that we need to call it as a constructor using the new operator. Replace the last two lines of the above code snippet with this:

const superman = new Hero("Superman", "Clark Kent");

Run the node index.js command again, and you will now get the expected output.

“this” inside constructors

JavaScript does not have any special constructor functions. All we can do is convert a function call into a constructor call using new operator as shown in the above section.

When a constructor call is made, a new object is created and set as the function’s this argument. The object is then implicitly returned from the function, unless we have another object that is being returned explicitly.

Inside the hero function write the following return statement:

return {
  heroName: "Batman",
  realName: "Bruce Wayne",

If we run the node command now, we will see that the above return statement overwrites the constructor call.

The only scenario where the return statement doesn’t overwrite the constructor call is if the return statement tries to return anything that is not an object. In this case, the object will contain the original values.

“this” in Methods

When calling a function as a method of an object, this refers to the object, which is then known as the receiver of the function call.

Here, I have a method dialogue inside an object called hero. The dialogue‘s this value then refers to hero itself. So hero here will be know as the receiver of the dialogue method’s call.

const hero = {
  heroName: "Batman",
  dialogue() {
    console.log(`I am ${this.heroName}!`);

This is very simply example. But in the real-world cases it can get very hard for our method to keep track of the receiver. Write the following snippet at the end of index.js.

const saying = hero.dialogue();

Here, I am storing the reference to dialogue inside another variable and calling the variable as a function. Run this with node and you will see that this returns an undefined because the method has lost track of the receiver. this now refers to global instead of hero.

The loss of receiver usually happens when we are passing a method as a callback to another. We can either solve this by adding a wrapper function or by using bind method to tie our this to a specific object.

call() and apply()

Though a function’s this value is set implicitly, we can also call function with explicit this argument call() and apply().

Lets restructure the previous sections code snippet like this:

function dialogue () {
  console.log (`I am ${this.heroName}`);
}const hero = {
  heroName: 'Batman',

We need to connect the dialogue function with the hero object as a receiver. To do so, we can either use call() or apply() like this:

// or

But if you are using call or apply outside of strict mode, then passing null or undefined using call or apply will be ignored by the JavaScript engine. This is one of the reasons why it is usually suggested to always write our code in strict mode.


When we pass a method as a callback to another function, there is always a risk of losing the intended receiver of the method, making the this argument set to the global object instead.

The bind() method allows us to permanently tie a this argument to a value. So in the below code snippet, bind will create a new dialogue function and set its this value to hero.

const hero = {
  heroName: "Batman",
  dialogue() {
    console.log(`I am ${this.heroName}`);
setTimeOut(hero.dialogue.bind(hero), 1000);

By doing so, our this cannot be changed by even call or apply methods.

Catching “this” inside an Arrow Function

Using this with an arrow function is quite different from using it with any other kind of JavaScript function. An arrow function uses the this value from its enclosing execution context, since it does have one of its own.

An arrow function permanently captures the this value, preventing apply or call from changing it later on.

To explain how this works with regards to the arrow functions, let’s write the arrow function shown below:

const batman = this;const bruce = () => {
  console.log(this === batman);

Here, we are storing the value of a this in a variable and then comparing the value with a this value that is inside an arrow function. Running node index.js in our terminal should give us true as output.

An arrow function’s this value cannot be set explicitly. Also, the arrow function will ignored any attempt from us at passing a value to this using methods like call, apply, and bind. An arrow function will refer to the this value that was set when the arrow function was created.

An arrow function can also not be used as a constructor. Hence, we cannot assign properties to this inside an arrow function.

So what can arrow functions do in regards to this?

Arrow functions can help us access this within a callback. To explain how this is done. Take a look at the counter object that I have written below:

const counter = {
  count: 0,
  increase() {
    setInterval(function() {
    }, 1000);

Running this code using node index.js will only give an increase list of NaNs. This is because this.count is not referring to the counter object. It actually refers to the global object.

To make this counter work, lets rewrite it using an arrow function.

const counter = {
  count: 0,
  increase () {
    setInterval (() => {
      console.log (++this.count);
    }, 1000);
counter.increase ();

Our callback now uses this binding from the increase method, and the counter now works as it should.

Note: Do not try to write this.count + 1 instead of ++this.count. The former of these two will only increase the value of count once, and return the that value on each iteration.

“this” in Classes

Classes are one of the most important parts of any JavaScript apps. Lets see how this behaves inside a class.

A class generally contains a constructor, where this would refer to any newly created object.

But in case of methods, this can also refer to any other value if the method is called as an ordinary function. And just like a method, classes can also lose track of the receiver.

Let’s re-create the Hero functions that we have seen earlier as a class. This class will contain a constructor and a dialogue() method. Finally, we create an instance of this class and call the dialogue method.

class Hero {
  constructor(heroName) {
    this.heroName = heroName;
  dialogue() {
    console.log(`I am ${this.heroName}`)
const batman = new Hero("Batman");

this inside the constructor refers to the newly created instance of that class. When we call batman.dialogue(), we invoke dialogue() as a method with batman as a receiver.

But if we store a reference to the dialogue() method, and later invoke it as a function, we once again lose the receiver of the method and the this argument now refers to undefined.

const say = batman.dialogue();

The reason for error is that JavaScript classes are implicitly in strict mode. We are invoking say() as an function without any autobinding. To solve this, we will need to manually bind() to tie this dialogue() function to batman.

const say = batman.dialogue.bind(batman);

We can also do this binding inside the constructor method.

javascript webdev

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

JavaScript Tutorial: if-else Statement in JavaScript

This JavaScript tutorial is a step by step guide on JavaScript If Else Statements. Learn how to use If Else in javascript and also JavaScript If Else Statements. if-else Statement in JavaScript. JavaScript's conditional statements: if; if-else; nested-if; if-else-if. These statements allow you to control the flow of your program's execution based upon conditions known only during run time.

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

Building a Powerful Virtual Machine in JavaScript

This JavaScript tutorial explains how to build a powerful Virtual Machine in JavaScript. A flexible, extensible, register-based virtual machine. Support for signed, unsigned and floating point operations. A call stack. Interrupt capabilities. Ability to do memory mapping for IO. An assembly language with macro and module support. A higher level, C like language. We'll use and expand the library from the parser combinators from scratch series. And finally, to be able to take the whole thing into the browser and exend it to create a sort of fantasy console - an emulator for a machine that never existed

Understanding JavaScript Decorators

Decorators are actually nothing more than functions that return another function, and that are called with the appropriate details of the item being decorated. Using decorators in your projects today requires some transpiler configuration. What is a Decorator? JavaScript Decorators and Property Descriptors. How to Write a Decorator. Handling API Errors. Decorating Classes. A Babel Workaround

JavaScript Map, Reduce, and Filter: What, Why and How to use it

Map, reduce, and filter are all array methods in JavaScript. In this JavaScript tutorial, you will learn what, why and how to use each one. Learn eight methods to iterate through an array in JavaScript! Methods include: forEach, map, filter, reduce, some, every, find, findIndex. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function