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:
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:
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:
call() can accept more than one argument, and if can accept more than one argument then you can pass those arguments as well!
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.
yourFunction.apply(object, [“thing1”, “thing2”, “thing3”])
Cool thing here with ES6 you can use the spread operator as well to spread in an array.
Some spread operator examples as well as some 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!