Horje
What is Apply in JavaScript ?

In JavaScript, the apply() method is used to invoke a function with a specified this value and an array or array-like object of arguments. It’s similar to the call() method but accepts arguments as an array. This method is particularly useful when the number of arguments is dynamic or when you want to pass an array of arguments to a function.

Syntax:

object.objectMethod.apply(objectInstance, arrayOfArguments)

Parameters: It takes two parameters:

  • ObjectInstance: It is an object which we want to use explicitly
  • Arguments: It is arguments that we want to pass to the calling function

Example: Here, apply() is used to invoke the greet() function with person as the this value and arguments provided in the args array.

Javascript

function greet(name, age) {
    console.log(`Hello, ${name}! You are ${age} years old.`);
}
 
const person = { name: 'Alice', age: 30 };
const args = ['Bob', 25];
 
// Using apply to invoke the greet function
// with arguments from the array
 
// Output: Hello, Bob! You are 25 years old.
greet.apply(person, args);

Output

Hello, Bob! You are 25 years old.





Reffered: https://www.geeksforgeeks.org


JavaScript

Related
What is Deep Copy In JavaScript ? What is Deep Copy In JavaScript ?
What is Shallow Copy in JavaScript ? What is Shallow Copy in JavaScript ?
What is Synchrounous Code Execution ? What is Synchrounous Code Execution ?
What is Null in JavaScript ? What is Null in JavaScript ?
What is Undefined in JavaScript ? What is Undefined in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11