JavaScript treats everything as an object, even functions, and every object has its own properties and methods. Function objects have both apply() and call() methods on them. However, there is confusion about the two functions in JavaScript. The main difference between them is how they handle function arguments. There is no difference between these two functions in how the arguments are passed to the called function, but the definition inside the function differs.
In addition to the first parameter, apply() requires an array as its second parameter. The arguments to the target method are represented as an array.
JavaScript call() Function: It uses given arguments and values to call a function
Syntax:
function.call(object, arg1, arg2)
Example:
Javascript
let obj = { fname: "neveropen" , mname: "for" , lname: "neveropen" , }; let display = function (str1, str2) { console.log(`${str1} ${str2} ${ this .fname + this .mname + this .lname}`); }; display.call(obj, "Welcome" , "to" ); |
Output:
Welcome to neveropen
JavaScript apply() Function: This method is used to call a function with arguments and values as arrays or array objects.
In both cases, the first argument will be the object reference that represents ‘this’ inside the called function. Therefore, the call() is different from apply(). Each can be applied to a function, which runs within the context of the first argument. In call(), the remaining arguments are passed into the function as is, whereas, in apply(), the second argument will be an array that the called function will unpack as arguments.
Syntax:
function.apply(object, [arg1, arg2])
Example:
Javascript
let obj = { fname: "neveropen" , mname: "for" , lname: "neveropen" , }; let display = function (str1, str2) { console.log(`${str1} ${str2} ${ this .fname + this .mname + this .lname}`); }; display.apply(obj, [ "Welcome" , "to" ]); |
Output:
Welcome to neveropen
Difference between Function.prototype.apply and Function.prototype.call:
Function.prototype.apply() |
Function.prototype.call() |
---|---|
Using the apply() method, one can call a function with a specified value as well as arguments provided in the form of an array (or object). | Using call(), a function is called with the given value and arguments. |
function.call(object, arg1, arg2) | function.apply(object, [arg1, arg2]) |