bluehost-banner
What is 'This' keyword in JavaScript

What is 'This' keyword in JavaScript

In this article, we will learn what is 'this' keyword in javascript.

What is This keyword in javascript?

This keyword refers to an object, that object which is executing the current bit of javascript code. 

In other words, every javascript function while executing has a reference to its current execution context, called this. Execution context means here is how the function is called.

Basically, The javascript this keyword refers to the object it belongs to.

It has different values depending on where it is used:

1) Alone, this refers to the global object

2) In a regular function, this refers to the global object

  function hello(){
    console.log(this);
  }

  hello();

The above function will return the windows object in the console.

3) In a method, this refers to the owner object

  const user = {
    name: "jigar",
    language: "English",
    greet: function () {
      console.log(`${this.name} knows ${this.language}`);
    },
  };

Now let’s execute the greet method.

 user.greet();

This prints:

jigar knows English

   When we are calling the greet() method using the user object, so the this keyword inside the method refers to the user object.  

4) In regular function, while having strict mode, this is undefined

  "use strict";
  function hello() {
    console.log(this);
  }

  hello();
//Output: undefined

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment