call and apply
Two methods let you run a function with a this you choose, and they differ only in how you hand over the arguments.
call invokes a function immediately with a this you supply and arguments listed individually. apply does the same but takes the arguments as an array. Both are how you borrow a method from one object and run it on another.
EXERCISE
1Running a Function with a this You Choose
Every function already has these two methods, inherited from Function.prototype, and both run the function right now.
Rule 2 from the last lesson said this can be supplied explicitly. call and apply are how you supply it.
They are not special syntax. They are ordinary methods sitting on Function.prototype, which means every function you write inherits them through the chain from Unit 1. That is worth noticing: the mechanism you learned in unit one is why the tool in unit two exists at all.
The basic form:
function greet() {
return `Hi, ${this.name}`;
}
console.log(greet.call({ name: "Ada" })); // Hi, Ada
console.log(greet.call({ name: "Bob" })); // Hi, Bob
The first argument becomes this. The function runs immediately and returns its value.
Extra arguments follow, one by one:
function introduce(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
console.log(introduce.call({ name: "Ada" }, "Hello", "!")); // Hello, Ada!
Read it as: run introduce, with this set to that object, passing "Hello" and "!" as the parameters.
apply is identical except the arguments arrive as an array:
console.log(introduce.apply({ name: "Ada" }, ["Hello", "!"])); // Hello, Ada!
// call -> arguments listed individually
// apply -> arguments in a single array
A mnemonic that has survived decades: a for array with apply, c for comma-separated with call. That is the entire difference. Same this, same immediate call, same return value.
When you genuinely need apply:
const numbers = [5, 2, 9, 1];
console.log(Math.max(numbers)); // NaN -- one array, not four numbers
console.log(Math.max.apply(null, numbers)); // 9 -- spread across parameters
console.log(Math.max(...numbers)); // 9 -- modern equivalent
Math.max wants separate arguments, and you have an array. Before spread syntax existed, apply was the only way to bridge that, which is why you will meet this line constantly in older code. null is passed as this because Math.max does not use it.
Today spread does the same job more clearly, so apply is mostly something you read rather than write.
Reach for call by default; you almost always know your arguments individually when you write the line. Reach for apply only when the arguments are already sitting in an array and you cannot use spread, which in modern code means essentially never. Recognising apply matters more than using it.
EXERCISE
2Borrowing a Method from Another Object
The real everyday use is running a method that lives on one object against a completely different one.
Because this is decided at the call site, a method is not permanently tied to the object it was written on. You can point it at anything with the right shape. This is called method borrowing, and it is the most common legitimate use of call.
Borrowing between your own objects:
const person = {
name: "Ada",
describe() {
return `${this.name} is ${this.age}`;
},
};
const dog = { name: "Rex", age: 3 };
console.log(person.describe.call(dog)); // Rex is 3
describe has no idea dog exists. It reads this.name and this.age, and dog happens to have both. Nothing was copied and dog gained no method.
Borrowing array methods, which is where you will really meet it:
function collect() {
// `arguments` is array-like: it has length and indexes, but no methods
console.log(arguments.length); // 3
// console.log(arguments.map(...)); // TypeError: not a function
const real = Array.prototype.slice.call(arguments);
console.log(real.map((n) => n * 2)); // [ 2, 4, 6 ]
}
collect(1, 2, 3);
slice only needs this to have a length and numeric keys. arguments has both, so borrowing works even though arguments is not an array.
The same trick applies to anything array-like, most often a list of DOM elements:
// const nodes = document.querySelectorAll("li"); // array-like, not an array
// const items = Array.prototype.map.call(nodes, (n) => n.textContent);
// Modern equivalents, which you should prefer:
// const items = Array.from(nodes).map((n) => n.textContent);
// const items = [...nodes].map((n) => n.textContent);
And one borrowing you will still write today:
const values = [1, "two", [3], { four: 4 }, null];
for (const v of values) {
console.log(Object.prototype.toString.call(v));
}
// [object Number]
// [object String]
// [object Array]
// [object Object]
// [object Null]
This is the most reliable type check in the language. It works where typeof says "object" for everything and where instanceof fails across iframes.
Pro Tip: Borrowing works because a method only ever asks for the properties it uses, not for a particular class. Whenever you see
Array.prototype.something.call(x)in a codebase, read it as: "x is array-like but not an array, and we want an array method anyway." Then check whetherArray.from(x)says it more plainly, because it usually does.
EXERCISE
3What You Pass as this, and What Arrives
The value you hand to call is not always the value that turns up inside the function, and the rules differ between strict and non-strict code.
There is one more thing to know before moving on, because it explains some results that otherwise look broken.
In strict mode, what you pass is what arrives:
"use strict";
function show() {
return this;
}
console.log(show.call(null)); // null
console.log(show.call(undefined)); // undefined
console.log(show.call(42)); // 42
console.log(typeof show.call(42)); // "number"
Straightforward. The value goes in untouched, including null and primitives. Every ES module is strict, so this is the behaviour you will normally see.
In non-strict code, the value is quietly transformed:
// Non-strict (an old script tag, not a module)
function show() {
return this;
}
show.call(null); // the global object, not null
show.call(undefined); // the global object
show.call(42); // a Number object wrapper, not the primitive 42
typeof show.call(42); // "object"
Two substitutions happen. null and undefined get replaced by the global object, and primitives get wrapped in their object form. This is called boxing, and it existed so that old code calling methods on primitives would not crash.
It is also why Math.max.apply(null, numbers) is safe. Math.max never touches this, so it does not care whether null arrives as null or as the global object.
Which leads to a habit worth adopting:
// When the function ignores `this`, people write null out of convention:
Math.max.apply(null, [3, 9, 1]);
// If you want to be explicit that no `this` is intended, use an object
// with nothing on it, which cannot accidentally expose anything:
Math.max.apply(Object.create(null), [3, 9, 1]);
// Or, in modern code, sidestep the question entirely:
Math.max(...[3, 9, 1]);
And a related gotcha with the number of arguments:
function count() {
return arguments.length;
}
console.log(count.call({})); // 0
console.log(count.call({}, "a", "b")); // 2
console.log(count.apply({}, [])); // 0
console.log(count.apply({})); // 0
console.log(count.apply({}, null)); // 0, null is accepted as "no arguments"
apply treats null and undefined in the array slot as an empty argument list rather than throwing, which is convenient and occasionally hides a bug where you meant to pass real arguments and passed a variable that turned out to be null.
In any file you write today, this arrives exactly as you passed it, because modules are strict. The boxing rules matter for reading older code and for understanding why null is the conventional filler when a function ignores this. If a call is behaving oddly in a legacy script, check whether the file is strict before suspecting anything else.
