JavaScript Interview Guide: Difference Between apply() and call() Methods
Introduction
In JavaScript, both apply()
and call()
are methods used to invoke functions while explicitly setting the this
context. While they serve similar purposes, their parameter handling differs. Understanding these differences is crucial for interviews and real-world coding scenarios.
Key Differences
Feature | call() |
apply() |
---|---|---|
Syntax | func.call(thisArg, arg1, arg2) |
func.apply(thisArg, [argsArray]) |
Arguments | Accepts arguments individually | Accepts arguments as an array |
Use Case | Fixed argument count | Dynamic/variable argument count |
Example: call()
function greet(message) {
console.log(`${message}, ${this.name}!`);
}
const user = { name: 'Alice' };
greet.call(user, 'Hello'); // Output: "Hello, Alice!"
Example: apply()
function sum(a, b, c) {
return a + b + c;
}
const numbers = [1, 2, 3];
console.log(sum.apply(null, numbers)); // Output: 6
When to Use Each?
- Use
call()
when arguments are known and fixed. - Use
apply()
when arguments are dynamic (e.g., from an array).
Modern Alternative: bind()
and Spread Operator
With ES6+, you can often replace apply()
with the spread operator:
sum(...numbers); // Same result as apply()
Interview Tip
Interviewers often ask: “How would you use call()
to borrow a method from another object?”
Example:
const car = { brand: 'Toyota' };
const showBrand = function() { console.log(this.brand); };
showBrand.call(car); // Output: "Toyota"
Conclusion
While call()
and apply()
achieve the same goal, their argument handling differs. Master both to write flexible code and ace JavaScript interviews.
Pro Tip: In modern JS, the spread operator reduces apply()
usage, but understanding these methods remains vital for legacy code and interviews.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.