Skip to content

JavaScript pass function as parameter with arguments

  • by

No specific syntax is required to pass a function as a parameter with arguments in JavaScript. Just pass it like a regular argument with some logic.

JavaScript pass function as parameter with arguments

Simple example code defines the function argument like a regular argument and calls that argument like a function.

<!DOCTYPE html>
<html>
<body>
  <script>

    function fubar(a, b, fn){
      console.log("argument function")
      return fn(a, b);
    }

    function add(c, d){
      console.log("add function")
      return c + d;
    }

    // pass the "add" function like a regular argument
    let result = fubar(100, 200, add);

    console.log(result);
  </script>

</body>
</html> 

Output:

JavaScript pass function as parameter with arguments

Another example:

// Function that takes another function as a parameter and arguments to pass
function executeFunctionWithArguments(func, arg1, arg2) {
  func(arg1, arg2);
}

// Example function to be passed as a parameter
function exampleFunction(arg1, arg2) {
  console.log(`Argument 1: ${arg1}`);
  console.log(`Argument 2: ${arg2}`);
}

// Calling the function with arguments
executeFunctionWithArguments(exampleFunction, 'Hello', 'World');

In this example, executeFunctionWithArguments is a function that takes three parameters: func, arg1, and arg2. It then calls the function func with the provided arguments arg1 and arg2.

The exampleFunction is a sample function that takes two arguments and logs them to the console.

Do comment if you have any doubts or suggestions on this JS function topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *