Mid-Level Core Concepts 6 min read

The 'this' Keyword in JavaScript — All the Rules

The Interview Question

How does the 'this' keyword work in JavaScript? What are the rules that determine its value?

Expert Answer

The value of 'this' in JavaScript is determined by HOW a function is called, not where it's defined. There are four rules, in order of precedence. First: new binding — when you call a function with 'new', 'this' is the newly created object. Second: explicit binding — call(), apply(), and bind() let you set 'this' explicitly. Third: implicit binding — when a function is called as a method of an object (obj.method()), 'this' is the object before the dot. Fourth: default binding — in non-strict mode, standalone function calls set 'this' to the global object (window/global); in strict mode, it's undefined. Arrow functions break all these rules — they don't have their own 'this'. Instead, they inherit 'this' from the enclosing lexical scope at the time they're created. This is why arrow functions are preferred for callbacks and event handlers inside classes and React components.

Key Points to Hit in Your Answer

  • this is determined by call-site, not definition-site (except arrow functions)
  • Precedence: new > explicit (call/apply/bind) > implicit (obj.method) > default
  • Arrow functions inherit this lexically — they have no own this binding
  • Common pitfall: extracting a method loses implicit binding (const fn = obj.method; fn())
  • bind() creates a new function with this permanently set
  • In React class components, you bind methods in constructor or use arrow functions

Code Example

const obj = {
  name: 'Goliath',
  greet() { return this.name; },
  greetArrow: () => this.name,  // inherits outer 'this'
};

obj.greet();       // 'Goliath' (implicit binding)
obj.greetArrow();  // undefined (arrow inherits module/global this)

const greet = obj.greet;
greet();           // undefined in strict mode (lost binding)

// Fix with bind
const bound = obj.greet.bind(obj);
bound();           // 'Goliath'

// Fix with arrow function in class
class Timer {
  constructor() { this.seconds = 0; }
  start() {
    // Arrow function inherits 'this' from start()
    setInterval(() => { this.seconds++; }, 1000);
  }
}

What Interviewers Are Really Looking For

Walk through the four rules with examples. The 'lost binding' problem (assigning a method to a variable) is an interview favorite. Explaining why arrow functions in React class components solve the binding problem shows practical application. If asked about call vs. apply vs. bind, know that call takes args individually, apply takes an array, and bind returns a new function.

Practice This Question with AI Grading

Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.

Start Practicing Free →