What is Function.apply in JavaScript?
The apply method calls the function with a given this value and an array-like object as an argument.
Syntax
apply(thisArg, argsArray)
-
thisArg: Thethisvalue on executing the function. It is an optional argument. However, ifthisArgis skipped, thethisvalue is:- non-strict mode - global object
- strict mode - undefined
-
argsArray: The arguments to be passed to a function. Arguments are passed as an array. -
The
applymethod returns the value returned by the function.
Example
var number = 10;
function test(...arguments) {
let max = arguments.length ? Math.max.apply(null, arguments) : 0;
return this.number + max;
}
console.log("Calling without thisArg");
console.log( test.apply() ); // 10
let obj = {number : 20};
console.log("Calling with thisArg");
console.log( test.apply(obj)); // 20
console.log("Calling with thisArg and arguments");
console.log( test.apply(obj, [100, 200, 300, 400]) ); // 420
In the code above, we have created a test function that will return the sum of the number property in the this object, and the largest value in the arguments passed.
-
First, we called the test function using the
applymethod without thethisArgargument. In this case, the global object is considered asthis. -
Then, we called the
testmethod by passingobjas athisArgvalue. Inside thetestfunction,objis considered asthisArg. -
Lastly, we passed
thisArgand arguments to thetestfunction.
Example with strict mode
"use strict" // strict mode
var number = 10;
function test() {
return this.number;
}
console.log("Calling without thisArg");
console.log( test.apply() ); // error
In the code above, we have called the test function without thisArg. This will result in an error because in strict mode, if we don’t pass the thisArg to the apply function, the this value inside the function is undefined. When trying to access the this value(undefined), we will get an error.
call()andapply()are identical in functionality. The only difference is thatcall()accepts a list of arguments; whereas,apply()accepts a single array of arguments.