šŸŽ‰ We just launched a new HTML course! Get 3 courses with 33% off! šŸŽ‰
Understanding Bind, Call and Apply in JavaScript

Understanding Bind, Call and Apply in JavaScript

Function methods demonstrated through Spongebob
Ferenc Almasi • šŸ”„ 2021 November 11 • šŸ“– 3 min read
  • twitter
  • facebook
šŸ“’ JavaScript

Like 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. Recently, I tried to clear the confusion around JavaScript’sĀ thisĀ keywordĀ and I briefly touched onĀ bindĀ andĀ call. But this time, I would like to give a more in-depth look on them with some addition aboutĀ apply.
Let’s go in order, according to the title, and start with bind. But first, we need some code to demonstrate all three of them, so take a look at the following:

const currentYear = new Date().getFullYear();

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

const patrick = {
    name: 'Patrick Star',
    dob: 1978,
    species: 'starfish',
    greet(qoute) {
        console.log(`Hey, it's me, ${this.name} and I'm ${currentYear - this.dob} years old`);
        qoute && console.log(qoute);
    }
};
Spongebob Squarepants.js Nothing out of the ordinary, just two aquatic animals
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Bind

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

// Since bind doesn't modify the original function, this.name will still be "Spongebob".
spongebob.greet.bind(patrick);
spongebob.greet(); // Hey, it's me, Spongebob...

// Assigning the bound greet to a variable and calling that will give back Patrick's details.
const greetPatrick = spongebob.greet.bind(patrick);
greetPatrick(); // Hey, it's me, Patrick...
bind.js
Copied to clipboard!

The above code example demonstrates thatĀ bindĀ does not change the actual function but creates a brand new one. When weĀ greetPatrick()Ā the second time, we get back Patrick’s details because of the bound context, even though we are callingĀ spongbob.greet.


Call

UnlikeĀ bind,Ā callĀ will actually call the function immediately with the specified context. Let’s take a look at the following:

// This will immediately calls greet with the context of patrick.
spongebob.greet.call(patrick);

// Since we call the function right away, the value of greetPatrick will be the return value
// When we don't have an explicit return statement eg.: 'return true;', "undefined" is returned implicitly
const greetPatrick = spongebob.greet.call(patrick);
console.log(greetPatrick); // undefined

spongebob.greet.call(spongebob, 'I\'m a good noodle!');
callMePatrick.js
Copied to clipboard!

On line:9, we call Spongebob with theĀ spongebobĀ context and for the argument, we are passing in a string. This line is essentially equivalent to the following:

spongebob.greet('I\'m a good noodle!');
greet.js
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

Apply

ApplyĀ functions asĀ call. The only difference between the two is that whileĀ callĀ accepts aĀ list of arguments,Ā applyĀ accepts anĀ array of arguments.

patrick.greet.apply(patrick, ['Is mayonnaise an instrument?']);
greet.js
Copied to clipboard!

Note the difference betweenĀ callĀ andĀ apply. One is called with an array while the other is not. If we were to have multiple arguments they would look the following:

// Accepts list of arguments
spongebob.greet.call(spongebob, 'Believe it or not', 'I\'m a good noodle!');

// Accepts array of arguments
patrick.greet.apply(patrick, ['Is mayonnaise an instrument?', 'Mayonnaise is not an instrument šŸ˜”']);
callVersusApply.js
Copied to clipboard!

I think that concludes the differences between the three. Let’s recap everything and draw the conclusion.


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 of the universe when talking aboutĀ callĀ andĀ apply


Which one to choose? It really depends on your choice.

Though if we look at which one performs better, it seems that theĀ winnerĀ isĀ call.

What Is ā€œthisā€, After All? — A Look at JavaScript this Keyword
  • twitter
  • facebook
šŸ“’ JavaScript
Did you find this page helpful?
šŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundreds of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro

Recommended