JavaScript Function Apply
Using apply() to call functions with array arguments
🔧 What is Function Apply?
The apply() method calls a function with a given 'this' value and arguments provided as an array. It's similar to call() but takes arguments as an array instead of individually.
// Basic apply() syntax
function greet(greeting, punctuation) {
return greeting + ' ' + this.name + punctuation;
}
const person = { name: 'Alice' };
const args = ['Hello', '!'];
const result = greet.apply(person, args);
console.log(result); // "Hello Alice!"
Output:
Hello Alice!
Key Apply Concepts
Array Arguments
Pass arguments as an array
func.apply(thisArg, [arg1, arg2])
This Context
Set the 'this' value for the function
func.apply(obj, args)
Math Operations
Great for Math.max, Math.min with arrays
Math.max.apply(null, [1,2,3])
Array Spreading
Convert array to individual arguments
func.apply(this, arrayArgs)
🔹 Basic Apply Example
Here's how apply() works with a simple function:
function introduce(greeting, hobby) {
return `${greeting}, I'm ${this.name} and I love ${hobby}`;
}
const person = { name: 'Bob' };
const arguments = ['Hi', 'coding'];
// Using apply with array of arguments
const message = introduce.apply(person, arguments);
console.log(message);
Output:
Hi, I'm Bob and I love coding
🔹 Apply vs Call Comparison
The main difference between apply() and call() is how arguments are passed:
function sum(a, b, c) {
return a + b + c;
}
// Using call() - arguments passed individually
const result1 = sum.call(null, 1, 2, 3);
// Using apply() - arguments passed as array
const result2 = sum.apply(null, [1, 2, 3]);
console.log(result1); // 6
console.log(result2); // 6
Output:
6
6
🔹 Practical Apply Examples
Common use cases for apply():
// 1. Finding max/min in array
const numbers = [5, 2, 8, 1, 9];
const max = Math.max.apply(null, numbers);
const min = Math.min.apply(null, numbers);
console.log('Max:', max); // 9
console.log('Min:', min); // 1
// 2. Array concatenation
const arr1 = [1, 2];
const arr2 = [3, 4, 5];
arr1.push.apply(arr1, arr2);
console.log(arr1); // [1, 2, 3, 4, 5]
// 3. Converting arguments to array
function showArgs() {
const argsArray = Array.prototype.slice.apply(arguments);
console.log(argsArray);
}
showArgs('a', 'b', 'c'); // ['a', 'b', 'c']
Output:
Max: 9
Min: 1
[1, 2, 3, 4, 5]
['a', 'b', 'c']