DEV Community

Cover image for Javascript call(), apply(), bind()
Josh Lee
Josh Lee

Posted on • Updated on

Javascript call(), apply(), bind()

If you’ve ever Googled Javascript interview questions, you’ve probably come across questions asking the interviewee to discuss the differences between Javascript’s call, apply, and bind functions.

At a first glance, these seem to be very confusing, but if you take the time to really study them, they’re pretty easy to understand.

Before we get started discussing the differences between call, apply, and bind, I’d like to give a shoutout to a course called JavaScript: The Advanced Concepts (2021). The lessons here really helped me increase my Javascript knowledge.

Call, apply, and bind are all centered around the ‘this’ keyword. I’ll write a more in-depth article covering the ‘this’ keyword in Javascript at later date, but you can just remember that ‘this’ refers to the object that calls the function with the ‘this’ keyword.

You might have code that looks like the following.

let person = {
  age: 30,
  name: "Josh"
}

person.greet = function() {
  console.log(`My name is ${this.name}.`)

}


person.greet();
Enter fullscreen mode Exit fullscreen mode

This would output: “My name is Josh.”

But what if you wanted to call that function, but use something else for ‘this’?

That’s where call and apply come in.

Let’s change our code a bit and add another person so our code looks like the following.

let josh = {
  age: 30,
  name: "Josh"
}

josh.greet = function() {
  console.log(`My name is ${this.name}.`)
}

let frank = {
  age: 25,
  name: "Frank"
}
Enter fullscreen mode Exit fullscreen mode

We can “hijack” the greet function from josh and let frank use it by using call or apply.

josh.greet.call(frank);

josh.greet.apply(frank);
Enter fullscreen mode Exit fullscreen mode

Both of these log “My name is Frank.”

Bind is very similar, but it’s used to store a function and then call at a later time.

let frankGreeting = josh.greet.bind(frank);

frankGreeting();
Enter fullscreen mode Exit fullscreen mode

We can pass arguments to these if we want. Let’s revise the main function we’re working with to the following.

josh.greet = function(lastName) {
   console.log(`My name is ${this.name} ${lastName}.`);
}
Enter fullscreen mode Exit fullscreen mode

We can use the call function like this.

josh.greet.call(frank, "smith");
Enter fullscreen mode Exit fullscreen mode

Or, if we want to use apply, we use an array for the arguments:

josh.greet.apply(frank, ["smith"]);
Enter fullscreen mode Exit fullscreen mode

And bind works similarly.

let frankGreeting = josh.greet.bind(frank);

frankGreeting("Smith");
Enter fullscreen mode Exit fullscreen mode

And that’s how call, apply, and bind work in Javascript! I think it’s pretty easy to wrap your head around when you break it down like this.

If you want to learn more about web development, make sure to follow me on Twitter.

Top comments (0)