Function.prototype.apply
The Function.prototype.apply method is a "close relative" of the call method, but with a slightly different way of passing arguments.
It is used to call a function with an explicitly specified context (this), but the arguments are passed as an array rather than comma-separated.
Syntax
func.apply(thisArg, [argsArray])thisArg- the object that becomesthisinside the function;argsArray- an array (or array-like object) with the arguments.
Example 1 - basic usage
function greet(city, job) {
console.log(`I am ${this.name} from ${city}, working as ${job}`);
}
const user = { name: 'Tim' };
greet.apply(user, ['Berlin', 'Frontend developer']);
// I am Tim from Berlin, working as Frontend developerThe same as:
greet.call(user, 'Berlin', 'Frontend developer');But the difference is in how arguments are passed:
call-> comma-separated,apply-> as an array.
Example 2 - usage with array-like objects
The apply method is often used when the arguments are already stored in an array or a similar structure (arguments, NodeList, etc.):
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum.apply(null, numbers)); // 6Example 3 - "borrowing" methods for array-like structures
function logArgs() {
console.log(arguments);
// turn arguments into an array using Array.prototype.slice
const arr = Array.prototype.slice.apply(arguments);
console.log(arr);
}
logArgs(1, 2, 3, 4);
// arguments → [1, 2, 3, 4]Here apply helps use an array method (slice) on the arguments object, which has no array methods of its own.
Example 4 - usage for Math.max / Math.min
The Math.max and Math.min methods do not accept an array, only listed numbers.
apply solves this elegantly:
const nums = [10, 20, 5, 40];
console.log(Math.max.apply(null, nums)); // 40
console.log(Math.min.apply(null, nums)); // 5The ES6 equivalent:
Math.max(...nums); // modern spread syntaxThe difference between apply, call, and bind
| Method | What it does | How arguments are passed | When it is called |
|---|---|---|---|
| call | Calls the function with the given this | Comma-separated | Immediately |
| apply | Calls the function with the given this | As an array | Immediately |
| bind | Creates a new function with this "bound" | Comma-separated | Later (on call) |
Features of thisArg
- If
thisArgisnullorundefined, then:- in strict mode (
'use strict') ->this = undefined - in non-strict mode ->
this = window(orglobalin Node.js)
- in strict mode (
function showThis() {
console.log(this);
}
showThis.apply(null); // window (in non-strict mode)Summary
| Property | Description |
|---|---|
| Purpose | Call a function with a given this |
| Way of passing arguments | Array or array-like object |
| Execution context | Global or set manually |
| When to use it | When the arguments are already collected into an array |
| Modern alternative | func(...args) (spread syntax) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.