How to create a function that invokes each provided function using JavaScript?

In JavaScript, functions are first-class objects, which means they can be passed as arguments to other functions. This powerful feature enables creating functions that can invoke multiple other functions systematically.

The "invoke-each" pattern creates a function that invokes each provided function with the same set of arguments. This pattern is particularly useful for executing multiple operations with shared data.

Why Use the Invoke-Each Pattern?

The invoke-each pattern serves several important purposes:

  • Abstraction: It hides the complexity of invoking multiple functions, making code cleaner and more maintainable.
  • Batch Operations: Execute multiple functions simultaneously with the same arguments, useful for logging, validation, or notifications.
  • Event Handling: Trigger multiple event handlers or callbacks from a single action.

Basic Implementation

The simplest approach uses a loop to iterate through functions and invoke each one:

<!DOCTYPE html>
<html>
<head>
   <title>Invoke Each Pattern</title>
</head>
<body>
   <div id="output"></div>
   <script>
      function invokeEach(functions, args) {
         for (var i = 0; i < functions.length; i++) {
            functions[i].apply(null, args);
         }
      }

      function greet(name) {
         document.getElementById("output").innerHTML += "Hello, " + name + "!<br>";
      }

      function welcome(name) {
         document.getElementById("output").innerHTML += "Welcome, " + name + "!<br>";
      }

      function farewell(name) {
         document.getElementById("output").innerHTML += "Goodbye, " + name + "!<br>";
      }

      // Invoke all functions with the same argument
      invokeEach([greet, welcome, farewell], ["Alice"]);
   </script>
</body>
</html>

Modern Implementation with Array Methods

Using modern JavaScript, we can implement this pattern more elegantly with forEach():

<!DOCTYPE html>
<html>
<head>
   <title>Modern Invoke Each</title>
</head>
<body>
   <div id="result"></div>
   <script>
      const invokeEach = (functions, ...args) => {
         functions.forEach(fn => fn(...args));
      };

      const logToPage = (message) => {
         document.getElementById("result").innerHTML += message + "<br>";
      };

      const mathOperations = [
         (a, b) => logToPage(`Sum: ${a + b}`),
         (a, b) => logToPage(`Product: ${a * b}`),
         (a, b) => logToPage(`Difference: ${a - b}`)
      ];

      invokeEach(mathOperations, 10, 3);
   </script>
</body>
</html>

Advanced Example: Function Pipeline

Here's a more practical example that demonstrates data processing with multiple functions:

<!DOCTYPE html>
<html>
<head>
   <title>Function Pipeline Example</title>
</head>
<body>
   <div id="pipeline-output"></div>
   <script>
      function invokeEach(functions, args) {
         const results = [];
         for (let i = 0; i < functions.length; i++) {
            results.push(functions[i].apply(null, args));
         }
         return results;
      }

      const processors = [
         (data) => {
            document.getElementById("pipeline-output").innerHTML += "Processing: " + data + "<br>";
            return data.toUpperCase();
         },
         (data) => {
            document.getElementById("pipeline-output").innerHTML += "Validating: " + data + "<br>";
            return data.length > 0;
         },
         (data) => {
            document.getElementById("pipeline-output").innerHTML += "Logging: " + data + "<br>";
            return "Logged: " + data;
         }
      ];

      const results = invokeEach(processors, ["hello world"]);
      document.getElementById("pipeline-output").innerHTML += "Results: " + JSON.stringify(results);
   </script>
</body>
</html>

Key Points

  • Use Function.prototype.apply() to pass arguments as an array
  • Modern implementations can use spread operator (...) for cleaner syntax
  • The pattern works well for batch operations, event handling, and data processing pipelines
  • Functions can return values that can be collected for further processing

Conclusion

The invoke-each pattern is a powerful JavaScript technique for executing multiple functions with shared arguments. It promotes code reusability and provides a clean way to handle batch operations or complex event handling scenarios.

Updated on: 2026-03-15T23:19:00+05:30

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements