A Quick Guide to Call(), Bind() and Apply() 
                                    Methods in JavaScript

A Quick Guide to Call(), Bind() and Apply() Methods in JavaScript

ยท

4 min read

Hey there!๐Ÿ‘‹๐Ÿป๐Ÿ™‚

I'm back again with a new javascript article. call(), bind() and apply() - you might have seen at least one of these three methods if you've spent quite some time in the Javascript realm. Well, maybe you're not using them that often in your day-to-day work but these are among the most frequently asked questions in any Javascript interview.๐Ÿคซ

Today is the day you learn them. ๐Ÿ’ช

In Javascript, functions are objects. Objects can have properties and methods. So, with every function, we get these three methods.

call().png

The call() and apply() methods set this inside the function and immediately execute that function. The only difference between call() and apply() is that the apply() method accepts an array of arguments instead of comma-separated values.

function.call(thisArg, arg1, agr2, ...)

function.apply(thisArg, [argumentsArr])

function.bind(thisArg, optionalArguments)

Revise "this" in the case of functions.

BUT... before starting let's revise this in case of functions. I have a dedicated blog on this keyword only you can read it."this"keyword

When executing a function, this is determined by how a function is called(runtime binding).

const user = {
  firstName: 'Chhakuli',
  lastName: 'Zingare',
  age: 21,
  getIntro: function() {
     console.log(`${this.firstName} ${this.lastName} is ${this.age} years old.`);
  }
}

user.getIntro(); // "Chhakuli Zingare is 21 years old."

function randomFunc() {
  console.log(this);
}

randomFunc(); // window object
  • In an object method: this refers to the owner object.
  • In a function(sloppy mode): this refers to global object.
  • In a function(strict mode): this is undefined.

That's enough knowledge for this.article. ๐Ÿ˜‰

Call() ๐Ÿค™

call(thisArg, arg1, arg2...): Call is a function with a provided this. Further arguments are provided as a comma-separated list.

Ways to remember: โ€œCallโ€™s arguments are separated by commasโ€.

Let's understand this with a very simple example.

function userIntro() {
  console.log(`${this.firstName} ${this.lastName}`);
};

const user = {
  firstName: 'Samiksha',
  lastName: 'Zingare'
};

userIntro(); // Output 1: undefined undefined

userIntro.call(user); // Output 2: Samiksha Zingare

userIntro.call({ firstName : 'Harry', lastName : 'Potter' }); // Output3: Harry Potter

Output: Screenshot (107).png

  1. We have a function userIntro() that will try to access this and console firstName and lastName. We have three outputs:
  2. We didn't use the call() method, so this by default will refer to the window object. window object doesn't have any properties like firstName or lastName. Hence, we got undefined undefined.
  3. This time we use call() and pass an object that has the required properties. this will now be user. Hence, we get a favorable output Samiksha Zingare.
  4. It's the same as above, just trying to prove how call() works. ๐Ÿ˜

You can also pass additional arguments in call():

function userIntro(city, state) {
  console.log(`${this.name} is from ${city}, ${state}`);
};

const user = {
  name: 'Sam',
  age: 21
}

userIntro.call(user, 'Nagpur', 'Maharashtra'); // Output: Sam is from Nagpur, Maharashtra

So, call() a function with this. ๐Ÿ‘€

bind()๐Ÿ”ผ

The bind function creates a copy of a function with a new value to the this present inside the calling function.

Ugh๐Ÿ˜ฉ, too much information to process at once. But since now we understand call(), let's use that knowledge to understand bind().

function getUser(user) {
  console.log(`${ user } is from ${ this.state }.`);
}

getUser.call({ state : 'Maharashtra' }, 'Sam'); // Output 1: Sam is from Maharashtra.

const userFromMaharashtra = getUser.bind({ state : 'Maharashtra' });

userFromMaharashtra('Sam'); // Output 2: Sam is from Maharashtra.
userFromMaharashtra('Chhaku'); // Output 3: Chhaku is from Maharashtra.

We made a function getUser() that is trying to access this. There are two outputs:

  1. We use call() and pass { state : 'Maharashtra' }(first argument) to be our this. The second argument will be user.
  2. We try to get the same output as 1 using bind().
  3. Using bind() we can bind this value to some function and get another function in return.
  4. In our case, we bind it with { state : 'Maharashtra' } and store the returned function in userFromMaharashtra.
  5. Now, when we call userFromMaharashtra, we just need to pass user argument. It will already have a this value.
  6. Just calling the same function again with a different user.

So, what are the differences b/w call() and bind()?

  • call() gets invoked immediately whereas bind() returns a function that we can invoke later.
  • call() takes additional arguments but bind() does not. call() doesn't make a copy of the function unlike bind().

Heyyyy! We're almost done.๐Ÿ˜‰

unnamed.png

apply()๐Ÿง

Apply() does the exact same thing as call(), but it requires the original functionโ€™s arguments to be passed in as an array.

function sum(num1, num2) {
  console.log(this + num1 + num2);
}

sum.call(2, 3, 4); // Output: 9
sum.apply(2, [3, 4]); // Output: 9

So why would you ever use apply()?๐Ÿค”

Well, it depends on how youโ€™d like your data to be shown. Having the arguments as an array can be useful for mathematical situations, or simply for making the separation between the โ€˜thisโ€™ reference and the original function arguments easier to distinguish.

If this was useful, please hit the heart and feel free to follow and read my other articles.

istockphoto-1249553369-612x612.jpg

Did you find this article valuable?

Support Chhakuli Zingare by becoming a sponsor. Any amount is appreciated!

ย