What is the use of the this keyword in JavaScript?

In JavaScript, the this keyword refers to the object that the current function or method is a property of. The value of this is determined at runtime and depends on how the function or method is invoked.

There are several use cases for the this keyword in JavaScript:

  1. Method Invocation:

    When a function is invoked as a method of an object, this refers to the object itself.

    For example:

    const person = {
      name: "John Doe",
      greeting: function () {
        console.log(`Hello ${this.name}`);
      },
    };
  2. Constructor Invocation:

    When a function is used as a constructor with the new keyword, this refers to the new object being constructed.

    For example:

    function Person(name) {
      this.name = name;
      this.greeting = function () {
        console.log(`Hello ${this.name}`);
      };
    }
    
    const person = new Person("John Doe");
    person.greeting();
  3. Function Invocation:

    When a function is invoked as a standalone function, this refers to the global object (window in browsers, or global in Node.js).

    For example:

    function greeting() {
      console.log(`Hello ${this.name}`);
    }
    greeting();
  4. Call and Apply Invocation:

    When a function is invoked using the call or apply method, this refers to the first argument passed to the method.

    For example:

    const person1 = {
      name: "Jane",
      greeting: function () {
        console.log(`Hello ${this.name}`);
      },
    };
    
    const person2 = {
      name: "John Doe",
    };
    
    person1.greeting.call(person2); // Hello John Doe
  5. Arrow Functions:

    In arrow functions, this is inherited from the surrounding scope.

    This means that the value of this in an arrow function is the same as the value of this in the outer function.

    For example:

    const person = {
      name: "John Doe",
      greeting: () => {
        console.log(`Hello ${this.name}`);
      },
    };
    
    person.greeting(); // Hello undefined

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: