Skip to content

call() and apply() in JavaScript

New Course Coming Soon:

Get Really Good at Git

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}`)
}, '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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: