Curriculum / Intermediate / Lesson 15

The `this` Keyword

How `this` is determined at call time β€” the source of most JS confusion.

15 of 30
intermediate πŸ“– 7 min read 🎯 4 questions

What is this?

this is a special keyword that refers to the object that is currently executing the function. Its value depends on how and where the function is called, not where it's defined.

πŸ’‘ Key insight this is determined at call time, not definition time. This is the source of most confusion.

Rules for this

Examples

// Global context
console.log(this); // window (in browser)

// Object method
let person = {
  name: "Alice",
  greet: function() {
    console.log(this.name);
  }
};
person.greet(); // "Alice"

// Arrow function (inherits parent's this)
let obj = {
  name: "Bob",
  greet: () => {
    console.log(this.name); // this is from outer scope
  }
};

Common Mistakes

Quick Quiz

1. What does this refer to in a method of an object?

2. How does this behave in arrow functions?

3. When is this determined?

Summary

Back to curriculum