JavaScript Function call() and apply()
Quick answer
call and apply invoke a callable immediately with an explicit this argument. They differ in the way arguments are supplied.
How it works
Use fn.call(receiver, a, b) for individual arguments and fn.apply(receiver, arrayLike) for an array-like argument list. Null or undefined as the apply list means no arguments. The target function still determines whether it uses the supplied this. Arrow functions ignore it.
function price(qty, fee) { return this.rate * qty + fee; }console.log(price.call({rate: 4}, 3, 2));Expected output in Node.js:
14call uses the supplied object and two separate arguments.
function total(a, b) { return this.base + a + b; }console.log(total.apply({base: 5}, {0: 2, 1: 4, length: 2}));Expected output in Node.js:
11apply reads indexed values according to length.
Common mistakes
apply accepts array-like objects, not arbitrary iterables merely because they are iterable.
Practice
Implement a price function that uses an explicit rate receiver.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Function call() and apply() — Knowledge Check
Apply the taught concept and predict the output.
Which method receives an array-like argument list?
When does call execute its target?
What does apply with null as its second argument supply?
What is the exact console output in JavaScript Function call() and apply() example 1?
function price(qty, fee) { return this.rate * qty + fee; }console.log(price.call({rate: 4}, 3, 2));What is the exact console output in JavaScript Function call() and apply() example 2?
function total(a, b) { return this.base + a + b; }console.log(total.apply({base: 5}, {0: 2, 1: 4, length: 2}));