DeployU
Interviews / Frontend Engineering / What is the `this` keyword and how does it work in JavaScript?

What is the `this` keyword and how does it work in JavaScript?

conceptual Core Concepts Interactive Quiz Code Examples

The Scenario

You are a frontend engineer at a social media company. You are writing a new component that has a method that needs to access a property of the component.

You are not sure how to use the this keyword to access the property.

The Challenge

Explain what the this keyword is in JavaScript and how its value is determined. What are the different ways to set the value of this, and what are the common pitfalls to avoid?

Wrong Approach

A junior engineer might be confused by the `this` keyword. They might not be aware of the different ways to set its value, or they might not know how to use it correctly in different contexts.

Right Approach

A senior engineer would have a deep understanding of the `this` keyword. They would be able to explain how its value is determined and would have a clear plan for how to use it correctly in different contexts.

Step 1: Understand How the Value of this is Determined

The value of the this keyword is determined by how a function is called.

How the function is calledValue of this
In the global contextThe global object (window in a browser, global in Node.js).
As a method of an objectThe object that the method was called on.
With newA new object that is created by the new operator.
With call, apply, or bindThe object that is passed as the first argument to call, apply, or bind.
As an event listenerThe element that the event was fired on.
As an arrow functionThe value of this from the enclosing lexical scope.

Step 2: Code Examples

Here are some code examples that show how the value of this is determined:

As a method of an object:

const myObject = {
  myMethod() {
    console.log(this);
  }
};

myObject.myMethod(); // myObject

With call, apply, or bind:

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

myFunction.call({ a: 1 }); // { a: 1 }

As an arrow function:

const myObject = {
  myMethod() {
    const myArrowFunction = () => {
      console.log(this);
    };
    myArrowFunction();
  }
};

myObject.myMethod(); // myObject

Practice Question

What will be logged to the console?