Skip to content

JavaScript function return function with parameters

  • by

In JavaScript, you can create a function that returns another function with parameters. This allows you to create functions that are customized for a specific use case and can be reused with different inputs.

To create a JavaScript function that returns another function with parameters, you can use the following syntax:

function outerFunction(parameter1) {
  return function innerFunction(parameter2) {
    // function code goes here
  }
}

To use this function, you can call outerFunction and pass in any required parameters, which will return innerFunction. You can then call innerFunction with any required parameters to execute the function’s code.

JavaScript function return function with parameters example

Simple example code.

function createMultiplier(multiplier) {
  return function(number) {
    return number * multiplier;
  };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5));
console.log(triple(5));

Output:

JavaScript function return function with parameters

Another example

function createCalculatorFunction(operator) {
  return function(num1, num2) {
    if (operator === '+') {
      return num1 + num2;
    } else if (operator === '-') {
      return num1 - num2;
    } else if (operator === '*') {
      return num1 * num2;
    } else if (operator === '/') {
      return num1 / num2;
    } else {
      return NaN;
    }
  };
}

const add = createCalculatorFunction('+');
const subtract = createCalculatorFunction('-');
const multiply = createCalculatorFunction('*');
const divide = createCalculatorFunction('/');

console.log(add(2, 3)); // Output: 5
console.log(subtract(6, 4)); // Output: 2
console.log(multiply(5, 8)); // Output: 40
console.log(divide(10, 2)); // Output: 5
console.log(divide(10, 0)); // Output: NaN

In this example, the createCalculatorFunction function takes an operator parameter and returns a new function that performs the specified arithmetic operation on its two arguments.

Comment if you have any doubts or suggestions on this JS function return 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 *