JavaScript(JS) function method - apply
The apply()
method is a function method in JavaScript that allows you to call a function with a given this
value and arguments provided as an array (or an array-like object).
The syntax for the apply()
method is:
function.apply(thisArg, [argsArray])
Here, thisArg
is the value that should be passed as the this
value when the function is executed. If you pass null
or undefined
, the global object will be used as the this
value.
The second parameter, argsArray
, is an optional array of arguments that should be passed to the function. If you don't want to pass any arguments, you can pass an empty array ([]
) or omit the parameter altogether.
For example, let's say we have a function sum()
that takes two arguments and returns their sum:
function sum(a, b) { return a + b; }
We can use the apply()
method to call the sum()
function with an array of arguments:
const numbers = [2, 3]; const result = sum.apply(null, numbers); console.log(result); // Output: 5
In this example, we pass null
as the this
value, since our sum()
function doesn't depend on the this
value. We then pass the array [2, 3]
as the second argument to apply()
. This array will be unpacked and passed as the arguments to the sum()
function, so it's equivalent to calling sum(2, 3)
directly.
Note that in modern JavaScript, you can use the spread operator (...
) instead of apply()
to achieve the same result:
const result = sum(...numbers); console.log(result); // Output: 5
This is shorter and more readable, so apply()
is not used as often as it used to be.