Javascript – call vs apply

Javascript call() and apply() can be used to invoke a function. They are mostly same. The only difference is in apply arguments are passed as array. That gives us more flexibility to invoke a function. Here is usage syntax.

call

fun.call(thisArg[, arg1[, arg2[, ...]]])

apply

fun.apply(thisArg, [argsArray])

call example

function greet (msg, name) {
  console.log(msg + " " + name)
}
greet.call(undefined, "Hello", "John");
Hello John
Env: node version v5.12.0

apply example

function greet (msg, name) {
  console.log(msg + " " + name)
}
greet.apply(undefined, ["Hello", "John"]);
Hello John
Env: node version v5.12.0
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments