apply() Function in JavaScript

The apply() method in JavaScript is used to invoke a function with a specified this value and arguments provided as an array (or array-like object). This is useful when you want to call a function with a specific context or when the arguments are unknown or dynamic.

Key Points about apply() Function:

apply() Syntax


function greet(name, age) {
    console.log('Hello, ' + name + '. You are ' + age + ' years old.');
}
            
greet.apply(null, ['Alice', 25]);

Example of Using apply() Function in JavaScript:

This example demonstrates the usage of the apply() method to call the greet() function with a dynamic set of arguments passed in an array.

apply() Syntax


function greet(name, age) {
    console.log('Hello, ' + name + '. You are ' + age + ' years old.');
}
greet.apply(null, ['Alice', 25]);

                        

Output

Hello, Alice. You are 25 years old.

Using apply() with Different Contexts Syntax

Syntax


const person = {
    name: 'Bob',
    greet: function(age) {
        console.log('Hello, ' + this.name + '. You are ' + age + ' years old.');
    }
};
person.greet.apply({ name: 'Alice' }, [30]);

Example of Using apply() with Different Contexts:

This example shows how the apply() method can be used to call the greet() method of the person object with a different this context.

Example


const person = {
    name: 'Bob',
    greet: function(age) {
    console.log('Hello, ' + this.name + '. You are ' + age + ' years old.');
    }
};
person.greet.apply({ name: 'Alice' }, [30]);

Output

Hello, Alice. You are 30 years old.