Problem Statement
What is the difference between call() and apply()?
Explanation
Call and apply both invoke functions with a specified this value, but differ in how they accept arguments.
Call takes individual arguments separated by commas. First argument is this, rest are function parameters.
Apply takes an array of arguments. First argument is this, second is an array containing all function parameters.
Both execute the function immediately.
Use call when you know arguments individually. Use apply when you have arguments in an array.
Modern JavaScript often uses spread operator instead of apply.
Remember: Call is comma separated, Apply takes an array.
Code Solution
SolutionRead Only
function introduce(greeting, profession) {
console.log(greeting + ', I am ' + this.name + ', a ' + profession);
}
const person = { name: 'John' };
// call - individual arguments
introduce.call(person, 'Hello', 'Developer');
// 'Hello, I am John, a Developer'
// apply - array of arguments
introduce.apply(person, ['Hello', 'Developer']);
// 'Hello, I am John, a Developer'
// Useful when you already have array
const args = ['Hi', 'Engineer'];
introduce.apply(person, args);
// Math.max with apply (classic use case)
const numbers = [5, 6, 2, 3, 7, 1];
// apply spreads array as individual arguments
const max = Math.max.apply(null, numbers);
console.log(max); // 7
// Modern alternative with spread operator
const max2 = Math.max(...numbers);
console.log(max2); // 7
// call with spread (modern approach)
introduce.call(person, ...args);
// Choosing between call and apply
function sum(a, b, c) {
return a + b + c;
}
// If you have values separately
const result1 = sum.call(null, 1, 2, 3); // 6
// If you have values in array
const nums = [1, 2, 3];
const result2 = sum.apply(null, nums); // 6
// Memory trick:
// call: c for comma
// apply: a for array