call vs apply
In short:
| Method | How arguments are passed | Call example |
|---|---|---|
call | listed comma-separated | func.call(thisArg, arg1, arg2, arg3) |
apply | passed as an array | func.apply(thisArg, [arg1, arg2, arg3]) |
Example for clarity
javascript
function greet(city, job) {
console.log(`I'm ${this.name} from ${city}, working as ${job}`);
}
const user = { name: 'Bohdan' };
// call - arguments comma-separated
greet.call(user, 'Kyiv', 'Frontend developer');
// apply - arguments as an array
greet.apply(user, ['Kyiv', 'Frontend developer']);Both calls output:
javascript
I'm Bohdan from Kyiv, working as Frontend developerWhen to use which
| Scenario | Better to use |
|---|---|
| Arguments are known in advance | call |
| Arguments are already in an array | apply |
Example: array of arguments
javascript
function sum(a, b, c) {
return a + b + c;
}
const nums = [1, 2, 3];
// Without apply - you'd have to write it manually
console.log(sum.call(null, nums[0], nums[1], nums[2]));
// With apply - just pass the array
console.log(sum.apply(null, nums)); // 6Modern equivalent with Spread
In modern JS (ES6+) apply is often replaced with the spread operator:
javascript
const nums = [1, 2, 3];
console.log(sum(...nums)); // the same result as sum.apply(null, nums)Summary
| Property | call | apply |
|---|---|---|
Context (this) | Explicitly given as the first argument | Same |
| Passing arguments | Comma-separated | As an array |
| Returns | The function's result | The function's result |
| Calls immediately | yes | yes |
| Modern alternative | Spread: func(...args) | Spread: func(...args) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.