Array Methods and Callback Context
What You'll Learn
You'll discover how array methods like forEach, map, and filter can silently break your method context when you pass callbacks that rely on this.
The Context Loss Problem
When you pass a method as a callback to array methods, you're extracting that function from its object—just like the method extraction problem you've learned. Array methods call your callback as a plain function, not as a method, so this becomes undefined (strict mode) or global (non-strict).
const calculator = {
multiplier: 10,
multiply(num) {
return num * this.multiplier;
},
multiplyAll(numbers) {
return numbers.map(this.multiply); // ❌ Lost 'this'!
}
};
calculator.multiplyAll([1, 2, 3]); // TypeError: Cannot read property 'multiplier' of undefined
The map method receives this.multiply as a standalone function and calls it without any object context.
The Solution: Explicit Binding
You must explicitly preserve the context using bind(), arrow functions, or the optional thisArg parameter many array methods accept:
// Solution 1: bind()
multiplyAll(numbers) {
return numbers.map(this.multiply.bind(this));
}
// Solution 2: Arrow function (lexical 'this')
multiplyAll(numbers) {
return numbers.map(num => this.multiply(num));
}
// Solution 3: thisArg parameter
multiplyAll(numbers) {
return numbers.map(this.multiply, this); // second argument!
}
All three preserve the correct this context, but arrow functions are most common in modern code.
Key Takeaway: Array method callbacks lose method context because they're called as plain functions—use bind(), arrow functions, or the thisArg parameter to preserve this.