call() and apply() Method in JavaScript

Shahrooz Me

Hi, I'm Shahrooz, a front-end developer. I'm the author of this blog, nice to meet you!

→ Follow me on Twitter!

Check out my ‘this and bind’ guide before start reading this article.

The bind() method returns a bound function but the call() method calls it immediately. If you don’t need to pass it around you only need call.

call() and apply() 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:

let car = {
  brand: 'BMW',
  color: 'red'
}

function drive(from, to) {
  console.log(`I am driving my ${this.color} ${this.brand} from ${from} to ${to}.`);
}

drive.call(car, 'San Francisco', 'New York'); // I am driving my red BMW from San Francisco to New York.
drive.apply(car, ['San Francisco', 'New York']); // I am driving my red BMW from San Francisco to New York.

Note that when using arrow functions this is not bound, so this method only works with regular functions.