Understanding the “this” Keyword in JavaScript

In the world of JavaScript, understanding context is paramount. The “this” keyword is the key to unlocking this contextual mystery. In this blog, we’ll delve into the depths of “this” in JavaScript, unravelling its nuances and shedding light on its behaviour in different scenarios.

“this” refers to the object that is currently executing the code. Its value dynamically changes based on how a function is invoked, rather than where it is defined. Let’s explore how “this” is determined in various contexts.

  • Global Context:

In the global context, outside of any function, ‘this’ refers to the global object. In a browser environment, ‘this’ refers to the ‘window’ object and ‘global’ in Node.js.

console.log(this === window); // true in browser environment
  • Function Context:

When invoked as a regular function, “this” refers to the global object in non-strict mode, and undefined in strict mode.

function regularFunction() {
    return this;
}
console.log(regularFunction() === window); // true in non-strict mode

Arrow functions however, retain the “this” value of their enclosing lexical context which means that ‘this’ within an arrow function is inherited from the surrounding code.

const arrowFunction = () => {
    return this;
};
console.log(arrowFunction() === window); // true

If a function is called using `call()`, `apply()`, or `bind()`, `this` is explicitly set to the first argument passed to `call()` or `apply()` or the value passed to `bind()`.

  • Method Context:

If a function is called as a method of an object, `this` refers to that object.

const obj = {
    name: "Billy",
    sing: function () {
      this.age = "20";
      console.log("a", this);
    },
  };
obj.sing();

Nested objects retain their own context, affecting the value of “this” accordingly.

const nestedObj = {
    name: 'Rowdy',
    nested: {
        name: 'Coder',
        greetNested() {
            return `Hello, ${this.name} from nested context!`;
        }
    }
};
console.log(nestedObj.nested.greetNested()); // Hello, Coder from nested context!
  • Constructor Context:

Constructor functions, used with the new keyword, create new objects with “this” referring to the newly instantiated object.

function Person(name) {
    this.name = name;
}

const john = new Person('John');
console.log(john.name); // John

Guess the output of the below code snippet based on the above information. The below output question was asked in the ServiceNow interview.

 const obj = {
    name: "Billy",
    sing: function () {
      this.age = "20";
      console.log("a", this);
      var anotherFunction = function () {
        this.age = "30";
        console.log("b", this);
      };
      anotherFunction();
    },
  };
  obj.sing();

The ‘this’ keyword in JavaScript holds the key to understanding context within functions. By grasping its behaviour in different scenarios, developers can write more robust and maintainable code. Experimenting with ‘this’ in your projects will deepen your understanding and unlock new possibilities in your JavaScript journey. Embrace this and let it guide you through the intricate world of JavaScript programming, feel free to comment your opinions.