Create a Function to Invoke Multiple Functions in JavaScript
In JavaScript, you can create a function that calls multiple functions by passing them as arguments and invoking each with the same set of parameters. This technique is useful for executing multiple operations with shared input values.
- Functions can be passed as arguments and stored in arrays for sequential execution.
- The main function iterates over each provided function and invokes it with the given arguments.
- Helps in building reusable, modular, and cleaner code when performing similar actions.
Functions can be defined in two ways:
[Approach 1]: Using a Higher-Order Function to Invoke Multiple Functions
- Function to separate even and odd numbers in an array.
- The findEven and findOdd functions take the same arguments by the segregateEvenodd function and are invoked in the segregateEvenodd function.
// Defined array
var ar =
[1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8];
function findEven(ar){
var res1 = [];
for (let geek = 0; geek < ar.length; geek++) {
if (ar[geek] % 2 === 0) {
res1.push(ar[geek]);
}
}
return res1;
}
function findOdd(ar){
var res2 = [];
for (let geek = 0; geek < ar.length; geek++) {
if (ar[geek] % 2 === 1) {
res2.push(ar[geek]);
}
}
return res2;
}
function segregateEvenOdd(ar) {
// Invoking findEven and findOdd functions
var even = findEven(ar);
var odd = findOdd(ar);
console.log("Before Segregation: ");
console.log(ar);
console.log("After Segregation: ");
console.log("Even integers: " + even);
console.log("Odd integers: " + odd);
}
// Invoker
segregateEvenOdd(ar);
Output
Before Segregation: [ 1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8 ] After Segregation: Even integers: 2,2,4,6,6,8,8,8 Odd integers: 1,3,5,7
[Approach 2]: Using Callback Functions to Process Array Data
- Function to find minimum and maximum in an array.
- The findMin and findMax functions take the same arguments by the FindMinMax function and are invoked in the FindMinMax function.
// Defined array
var ar = [20, 30, 40, 50, 60, -20, -40, 90, 100];
function findMin(ar) {
var res1 = Number.MAX_VALUE;;
for (let geek = 0; geek < ar.length; geek++) {
if (ar[geek] < res1) {
res1 = ar[geek];
}
}
return res1;
}
function findMax(ar) {
var res2 = Number.MIN_VALUE;
for (let geek = 0; geek < ar.length; geek++) {
if (ar[geek] > res2) {
res2 = ar[geek];
}
}
return res2;
}
function FindMinMax(ar) {
// Invoking findMin and findMax functions
var min = findMin(ar);
var max = findMax(ar);
console.log("Given array : ");
console.log(ar);
console.log("Minimum in the array: " + min);
console.log("Maximum in the array: " + max);
}
// Invoker
FindMinMax(ar);
Output
Given array : [ 20, 30, 40, 50, 60, -20, -40, 90, 100 ] Minimum in the array: -40 Maximum in the array: 100