Understanding Bind, Call and Apply in JavaScript

Understanding Bind, Call and Apply in JavaScript

Function methods demonstrated through Spongebob
Ferenc Almasi β€’ Last updated 2024 February 09 β€’ Read time 5 min read
Understanding the differences between bind, call, and apply should be an essential toolkit in your pocket. Learn what they mean in JavaScript.

Just as applying cold water to a burned area in the real world, we can also apply additional information to our function calls in the digital world through various function methods. In this tutorial, we'll take an in-depth look at what apply, call, and bind are in JavaScript and how they work.

This tutorial heavily uses the this keyword in JavaScript. If you're unfamiliar with how the this keyword works, check out the tutorial below first.

What Is β€œthis”, After All? β€” A Look at JavaScript this Keyword

Let’s go in order, and start with bind. But first, we need some code to demonstrate all three of them, so we'll use the following two objects as examples:

Copied to clipboard! Playground
const currentYear = new Date().getFullYear()

const spongebob = {
    name: 'Spongebob Squarepants',
    dob: 1986,
    species: 'sea sponge',
    greet(quote) {
        console.log(`Hey, it's me, ${this.name} and I'm ${currentYear - this.dob} years old`)
        quote && console.log(quote) // If we have a quote, log it out
    }
}

const patrick = {
    name: 'Patrick Star',
    dob: 1978,
    species: 'starfish',
    greet(quote) {
        console.log(`Hey, it's me, ${this.name} and I'm ${currentYear - this.dob} years old`)
        quote && console.log(quote)
    }
}
Spongebob Squarepants.js
Example objects used for explaining bind, call, and apply

To demonstrate the functionality of bind, call, and apply, we'll see how we can modify the context (the properties) of the above objects, such as their name, dob, or species properties. We also have a greet function, so that we can demonstrate how to modify the context of object methods too.


Bind

bind is used in JavaScript to bind certain contexts to a function. When we have a function called lofi and we call it like lofi.bind(chill), we are creating a new function where the context of this is set to the value of chill. Keep in mind that this does not modify the original function nor will it call:

  • index.js index.js
  • data.js data.js
🚫 Refresh console

The above code example demonstrates that bind does not change the actual function but creates a brand-new one. On line 4, we use the bind method to create a new context. However, when calling the greet function on line 5, we still get the original context.

To use the modified context, we need to assign the bind call to a variable. This is what we did on line 8. When we call greetPatrick() the second time, we get back Patrick’s details because of the bound context, even though we are calling spongbob.greet.


Call

Unlike bindcall will call the function immediately with the specified context. Let’s take a look at a couple of examples to better understand how call differs from bind. Take a look at the following code:

  • index.js index.js
  • data.js data.js
🚫 Refresh console
  • Line 4: We call the greet method with the call function method, passing in patrick as a parameter (for the context). This will immediately execute the function β€” unlike bind β€” creating a console.log.
  • Line 7: When assigning the call method to a variable, we'll also get another line logged to the console as the function is executed again, regardless of the variable assignment.
  • Line 10: If we log the greetPatrick variable to the console, it'll return undefined. This is because the greet method doesn't return anything. If we don't have an explicit return statement in a function, for example, return true, undefined is returned implicitly.
  • Line 13: When we pass more than one parameter to call, the rest will be forwarded to the function. Notice that the greet method accepts a quote parameter. The second string will be passed as the quote. This line is essentially equivalent to the following:
Copied to clipboard!
spongebob.greet('One eternity later')
Calling the greet method with a parameter
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Apply

The apply function method is similar to call. The only difference between the two is that call accepts a list of arguments, while apply accepts an array of arguments:

Copied to clipboard!
patrick.greet.apply(patrick, ['One eternity later']);
apply accepts and array of arguments

Note the difference between call and apply. One is called with an array while the other is not. There's no difference between their functionality; the only difference is the way they accept arguments. If we were to have multiple arguments they would look like the following:

Copied to clipboard! Playground
// Accepts list of arguments
spongebob.greet.call(spongebob, '2000 years later', 'One eternity later');

// Accepts array of arguments
patrick.greet.apply(patrick, ['2000 years later', 'One eternity later']);
Passing multiple parameters to call and apply

Conclusion

Let’s recap everything and draw a conclusion.

  • Use bind when you want to bind a context to a function you want to call later.
  • Use call or apply if you want to invoke the function immediately.

And the greatest question when it comes to call and apply: which one should you use? It really depends on your personal choice. However, if we look at which one performs better, call executes faster most of the time:

🚫 Refresh console

Is there anything else you'd like to know about bind, call, and apply in JavaScript? Let us know in the comments below! The use of the this keyword heavily ties into this topic. If you're unfamiliar with how this works, be sure to check out the following tutorial:

What Is β€œthis”, After All? β€” A Look at JavaScript this Keyword
  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.