Medium'this' Binding🐛 Debug Challenge

Regular callback inside method loses this

Buggy Code — Can you spot the issue?

const counter = {
  value: 42,
  logAfterDelay() {
    setTimeout(function() {
      console.log(this && this.value);
    }, 0);
  },
};

counter.logAfterDelay();

Fixed Code

const counter = {
  value: 42,
  logAfterDelay() {
    setTimeout(() => {
      console.log(this.value);
    }, 0);
  },
};

counter.logAfterDelay();

Bug Explained

Bug: Regular function callbacks lose their this context. Inside the setTimeout, this is undefined — not counter.

Explanation: Arrow function callbacks inherit this from their enclosing scope — here, the logAfterDelay method where this is counter.

Key Insight: Use arrow functions as callbacks inside methods to preserve the outer this.

More 'this' Binding Debug Challenges

EasyMethod detached from object loses thisEasyArrow function as object method has no own thisMediumbind is permanent — call cannot override it

Practice spotting bugs live →

38 debug challenges with AI hints

🐛 Try Debug Lab