call, apply, and bind are Function methods in JavaScript used to explicitly control the value of this inside a function.
πΉ Why Do We Need call, apply, bind?
In JavaScript, this depends on how a function is called, not where it is defined.
These methods let us manually set this.
πΉ call() — Invoke Immediately (Comma-separated arguments)
function greet(city, country) {
console.log(this.name, city, country);
}
const user = { name: "Teekam" };
greet.call(user, "Delhi", "India");
β Output
Teekam Delhi India
π§ When to use call
- Borrow methods from another object
- Pass arguments individually
- Immediate execution
πΉ apply() — Invoke Immediately (Arguments as Array)
greet.apply(user, ["Delhi", "India"]);
π§ Difference from call
- Arguments passed as array
- Useful when arguments are dynamic
πΉ bind() — Returns a New Function (Does NOT Execute)
const boundGreet = greet.bind(user, "Delhi", "India");
boundGreet();
π§ When to use bind
- Event handlers
- Call function later
- Preserve
thispermanently
π Key Differences (Quick Table)
| Method | Executes Immediately | Arguments | Returns |
|---|---|---|---|
| call | β Yes | Comma-separated | Function result |
| apply | β Yes | Array | Function result |
| bind | β No | Comma / Array | New function |
π§ͺ Real-World Examples
β Method Borrowing
const person1 = { name: "A" };
const person2 = { name: "B" };
function sayName() {
console.log(this.name);
}
sayName.call(person1); // A
sayName.call(person2); // B
β apply with Math.max
Math.max.apply(null, [1, 5, 3]); // 5
β bind in Event Handler
button.onclick = obj.handleClick.bind(obj);
π― Short Interview Answer
callandapplyinvoke a function immediately while settingthis.calltakes arguments individually,applytakes them as an array.bindreturns a new function withthispermanently bound, used when execution needs to be deferred.
β One-line summary
call and apply run now, bind runs later — all control this.