Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
JavaScript for Frontend Interviews
  1. 1.Introduction to JavaScript & Setup
  2. 2.Variables and Data Types
  3. 3.Operators and Expressions
  4. 4.Control Flow: Conditionals
  5. 5.Control Flow: Loops
  6. 6.Functions: Basics
  7. 7.Arrays and Objects
  8. 8.Higher-Order Functions & Callbacks
  9. 9.Scope and Closures
  10. 10.`this` Keyword and Context
  11. 11.Asynchronous JavaScript: Callbacks & Promises
  12. 12.ES6+ Features (Part 1)
  13. 13.ES6+ Features (Part 2)
  14. 14.Error Handling & Debugging
  15. 15.Asynchronous JavaScript: Async/Await
  16. 16.Prototypal Inheritance & `new` Keyword
  17. 17.Event Loop, Microtasks & Macrotasks
  18. 18.Working with the DOM
  19. 19.Advanced Array Methods & Data Structures
  20. 20.Frontend Interview Prep & Best Practices
JavaScript for Frontend Interviews
10

JavaScript · Lesson 10 of 20 · 3 min

`this` Keyword and Context

This isn't an academic exercise. Getting this wrong in an interview signals a weak grasp of JavaScript's runtime model.

The value of this is determined by how a function is called, not where it is defined. This is called the "call-site". If you can find the call-site, you can determine this.

There is a clear hierarchy of rules. To find the value of this, you check these rules in order.

The Four Binding Rules, in Order of Precedence

  1. new Binding: If a function is called with the new keyword (const c = new Car()), this inside that function is the newly created object. This rule wins over all others.

  2. Explicit Binding: You can force this to be a specific object using call, apply, or bind.

    • fn.call(thisArg, arg1, arg2): Calls fn immediately with this set to thisArg.
    • fn.apply(thisArg, [arg1, arg2]): Same as call, but takes arguments as an array.
    • fn.bind(thisArg): Does not call the function. It returns a new function where this is permanently locked to thisArg. This is what you use for callbacks and event handlers.
  3. Implicit Binding: When you call a function as a method of an object (obj.method()), this is the object to the left of the dot (obj).

    The classic trap: The context is lost if you pass the method without calling it. setTimeout(obj.method, 1000) detaches method from obj. When setTimeout's internals eventually invoke it, the call-site is just method(), which falls through to the default binding rule.

  4. Default Binding: If none of the other rules apply (a plain function call like myFunction()), this is the global object (window in browsers). However, in strict mode, this is undefined. Modern JavaScript (modules, classes) runs in strict mode by default, so you should almost always assume this will be undefined.

The Exception: Arrow Functions are Lexical

Arrow functions do not have their own this context. They ignore all four rules above.

Instead, this is resolved lexically, just like any other variable. It takes the value of this from its surrounding scope at the time it is defined. This makes them ideal for callbacks inside methods, as they automatically capture the correct this from the parent scope.

The trap: Do not use an arrow function for an object method if you need this to refer to the object itself. The arrow function will capture this from the scope where the object is defined (often the global scope), not from the object at call time.

Code Walkthrough: Rules in Conflict

This example demonstrates the rules, the common "lost context" problem, and the solutions.

'use strict';

const user = {
    name: "Alice",
    // Rule 3: Implicit Binding
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    },
    // Demonstrates losing and preserving context
    introduce: function() {
        console.log(`My name is ${this.name}.`);

        function innerFunction() {
            // This is a plain function call, so it's Rule 4: Default Binding.
            // `this` is `undefined` in strict mode.
            // The optional chaining `?.` prevents a TypeError.
            console.log(`Inside innerFunction, my name is ${this?.name}`);
        }
        innerFunction();

        const innerArrow = () => {
            // Arrow function inherits `this` from the `introduce` scope.
            // In the call to `user.introduce()`, `this` is `user`.
            console.log(`Inside innerArrow, my name is ${this.name}`);
        };
        innerArrow();
    }
};

// Implicit Binding: `this` is `user` because of the `user.` call-site.
user.greet();
//> Hello, my name is Alice

// `introduce` is called on `user`, so `this` is `user` inside `introduce`.
// But the nested `innerFunction` loses that context.
user.introduce();
//> My name is Alice.
//> Inside innerFunction, my name is undefined
//> Inside innerArrow, my name is Alice

// Rule 2: Explicit Binding
const otherUser = { name: "Bob" };
user.greet.call(otherUser);
//> Hello, my name is Bob

// Rule 1: `new` Binding
function Person(name) {
    // When called with `new`, `this` is the new object being created.
    this.name = name;
}
const person = new Person("Charlie");
console.log(`New binding: ${person.name}`);
//> New binding: Charlie

Visualizing the Precedence

This flowchart shows the order of operations for determining this.

Try it

Refactor the user.introduce method from the code example. Remove the innerFunction and innerArrow helpers. Instead, use setTimeout to log the user's name after 100ms. First, pass user.greet directly as the callback to see it fail. Then, fix it once using .bind(user) and a second time using an arrow function wrapper.

Next: Asynchronous JavaScript: Callbacks & Promises, where controlling this is critical.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Scope and Closures

Next

Asynchronous JavaScript: Callbacks & Promises