JavaScript apply() Method Guide
In JavaScript, the apply() method is a built-in method of the Function object, used to call a function within a specified scope and pass an array (or array-like object) as the parameters to that function. The syntax of the apply() method is as follows:
function.apply(thisArg, [argsArray])
- function: the function to be called
- thisArg: optional parameter that specifies the value of ‘this’ used in the function
- argsArray: an array or array-like object containing the parameters to be passed to the function.
For example, suppose there is a function as follows:
function greet(name) {
console.log(`Hello, ${name}!`);
}
We can utilize the apply() method to invoke this function and pass in one parameter:
greet.apply(null, ['Alice']);
In this example, the apply() method will call the greet function with null as the this value, and pass an array containing the string ‘Alice’ as a parameter. This will print out “Hello, Alice!”.