How to use Call and Apply in JavaScript

If you have been writing or starting to learn JavaScript, it is likely you have seen call() and apply()…if not, you will!

Adi S
Adi S
Dec 4, 2019 · 3 min read

Let’s go over both of them and see the differences. They are definitely similar but have different purposes.

How To Use call()

To create a simple example, I will make an object and function:

What does this return?

If you thought this returns:

I am a persian cat and my name is bubbles

That would be wrong. You actually get an error message:

To fix this error, we have to call the function speakCat with the catObject:

Now you should get the expected outcome

Our code above did not work at first because this is not defined. For this example in JS, this would refer to the global object. Since I am on a browser (Chrome 🥳), the global object is window. So, we could make the above code work by replacing this with window:

Can not just replace ‘this’ literally but have to modify the object and notation a bit

call() can accept more than one argument, and if can accept more than one argument then you can pass those arguments as well!

speakDog() is accepting multiple arguments and passing them to call()

How to use apply()

apply() is similar to call() but there are some differences. The way apply accepts arguments is in the form of an array. Notice that in call, arguments were accepted just separated by commas.

Cool thing here with ES6 you can use the spread operator as well to spread in an array.

apply() requires arguments in an array format

Some spread operator examples as well as some with built in JS functions:

Spread operator examples and some more with built-in JS functions

To remember which notation is used for call and apply, *I did not come up with this, I forgot where I read it, maybe StackOverflow*:

call uses commas and apply uses arrays.

I hope this helps you understand the difference between call and apply, how to use them and how to use the spread operator (ES6) with apply!

JavaScript in Plain English

Learn the web's most important programming language.

Adi S

Written by

Adi S

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade