Trivia Questions1 min readPremium

What’s the difference between call and apply?

Understanding the Difference Between call and apply in JavaScript

In JavaScript, the call and apply methods are powerful tools for invoking functions with explicit context and arguments. While they serve a similar purpose, the main difference lies in how they handle arguments passed to the target function. MDN documents both call() and apply().

Using call

The call method allows you to invoke a function with a specified this value and individual arguments. This method is particularly useful when you know the number of arguments and want to pass them directly.

function greet(greeting, name) {
  console.log(greeting + ", " + name + "!");
}

greet.call(null, "Hello", "John"); // Output: "Hello, John!"

Using apply

Conversely, the apply method also invokes a function with a specified this value, but it accepts an array of arguments. This approach is ideal when the number of arguments is unknown or when dealing with an array of arguments.

function greet(greeting, name) {
  console.log(greeting + ", " + name + "!");
}

greet.apply(null, ["Hello", "John"]); // Output: "Hello, John!"

Choosing Between call and apply

Deciding whether to use call or apply depends on the situation at hand. If you’re dealing with a fixed... premium content.

Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users