How to use the apply() method In Javascript
This method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed. The apply() method is used on the function that has to be passed as the arguments array. The first parameter is specified as ‘null’ and the second parameter is specified with the arguments array. This will call the function with the specified arguments array.
Syntax:
arrayToPass = [1, "Two", 3];
unmodifiableFunction.apply(null, arrayToPass);
Example: In this example, we will pass the array using the apply method.
function passToFunction() {
arrayToPass = [1, "Two", 3];
unmodifiableFunction.apply(null, arrayToPass);
}
function unmodifiableFunction(a, b, c) {
console.log(`First value is: ${a}
Second value is: ${b}
Third value is: ${c}`)
}
passToFunction()
Output
First value is: 1 Second value is: Two Third value is: 3
How to pass an array as a function parameter in JavaScript ?
In this article, we will learn how to pass an array as a function parameter in JavaScript.
This can be done by two methods:
Table of Content
- Method 1: Using the apply() method
- Method 2: Using the spread syntax:
- Method 3: Using the call() Method
Contact Us