DEV Community

Mohit Decodes
Mohit Decodes

Posted on

call, apply, and bind in JavaScript — Explained with Simple Examples

In JavaScript, functions are first-class objects. That means they can be passed around, assigned to variables, and — most importantly — called with different contexts using call(), apply(), and bind().

Image description

Let’s break it down simply. 👇


Why Do We Need call, apply, and bind?

Sometimes, you want to change the value of this inside a function — especially when you borrow a method from another object or use it as a callback.


call() Method

Syntax:

functionName.call(thisArg, arg1, arg2, ...) 
Enter fullscreen mode Exit fullscreen mode

Example:

const user1 = { name: "Mohit", }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } greet.call(user1, "Hello"); // Output: Hello, Mohit 
Enter fullscreen mode Exit fullscreen mode

call() immediately invokes the function and sets this to user1.


apply() Method

Syntax:

functionName.apply(thisArg, [arg1, arg2, ...]) 
Enter fullscreen mode Exit fullscreen mode

Same as call(), but it takes arguments as an array.

Example:

const user2 = { name: "Kumar", }; greet.apply(user2, ["Hi"]); // Output: Hi, Kumar 
Enter fullscreen mode Exit fullscreen mode

apply() is great when you already have arguments in an array.


bind() Method

Syntax:

const newFunc = functionName.bind(thisArg, arg1, arg2, ...) 
Enter fullscreen mode Exit fullscreen mode

❗ Difference: bind() does not invoke the function immediately — it returns a new function.

Example:

const user3 = { name: "React Dev", }; const greetUser3 = greet.bind(user3, "Welcome"); greetUser3(); // Output: Welcome, React Dev 
Enter fullscreen mode Exit fullscreen mode

Useful when you want to call the function later, but with a specific this.


Quick Comparison Table

Method Changes this? Invokes Function? Arguments Format
call Yes Yes Comma-separated
apply Yes Yes Array
bind Yes No Comma-separated (then invoked later)

Real-World Use Case (Method Borrowing)

const person = { name: "Mohit", sayHello: function (age) { console.log(`Hi, I'm ${this.name} and I'm ${age} years old.`); }, }; const anotherPerson = { name: "Rahul", }; person.sayHello.call(anotherPerson, 30); // Hi, I'm Rahul and I'm 30 years old. 
Enter fullscreen mode Exit fullscreen mode

Summary

  • Use call() or apply() when you want to invoke a function immediately with a different context.
  • Use bind() when you want to create a new function with a bound context for later use.

Practice Tip: Try rewriting small functions using all three to see how they behave differently.

📺 Want a visual explanation? Watch the upcoming YouTube Video on call, apply, and bind on Mohit Decodes

Got stuck? Want to showcase your version? Drop a link or comment below.
📲 Follow me on Instagram or WhatsApp for daily frontend tips.


👍 If this helped, drop a ❤️ or follow me for more quick JS tips!

Top comments (0)