call() and apply() in JavaScript
Find out how to use call() and apply() and their difference in JavaScript
call() and apply() are two functions that JavaScript offers to perform a very specific task: call a function and set its this value.
Check out my “this” guide to know all the details about this particular variable
A function can use the this value for many different use cases. The problem is that it’s given by the environment and cannot be changed from the outside, except when using call() or apply().
When using those methods, you can pass in an additional object that will be used as this in the function invoked.
Those functions perform the same thing, but have a difference. In call() you can pass the function parameters as a comma separated list of parameters, taking as many parameters as you need, while in apply() you pass a single array that contains the parameters:
const car = {
brand: 'Ford',
model: 'Fiesta'
}
const drive = function(from, to, kms) {
console.log(`Driving for ${kms} kilometers from ${from} to ${to} with my car, a ${this.brand} ${this.model}`)
}
drive.call(car, 'Milan', 'Rome', 568)
drive.apply(car, ['Milan', 'Rome', 568])
Note that when using arrow functions this is not bound, so this method only works with regular functions.
download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.