0

How do i eliminate functions defined in-place as parameters? As in, the function that returns the addition of its two parameters should be coded as a named function and the other function should be coded as an anonymous function assigned to a variable.

var outputAreaRef = document.getElementById("outputArea");
var output = "";

function flexible(fOperation, operand1, operand2)
{
var result  = fOperation(operand1, operand2);

return result;
}

output += flexible(function(num1, num2) {return num1 + num2}, 3, 5) + "<br/>";
output += flexible(function(num1, num2) {return num1 * num2}, 3, 5) + "<br/>"; 

outputAreaRef.innerHTML = output;

2 Answers2

2

If I understood the question correctly you are looking for something like:

 var outputAreaRef = document.getElementById("outputArea");
 var output = "";

 function flexible(fOperation, operand1, operand2) {
     var result = fOperation(operand1, operand2);
     return result;
 }

 function sum(a, b) {
     return a + b;
 }

 output += flexible(sum, 3, 5) + "<br/>";
 output += flexible(function (num1, num2) {
     return num1 * num2
 }, 3, 5) + "<br/>";

 outputAreaRef.innerHTML = output;

see https://jsfiddle.net/nwp1k93f/

In addition, you may also have a look at

Note:

Community
  • 1
  • 1
Philipp
  • 1,289
  • 1
  • 16
  • 37
0

Just define them as you would any other functions. There's nothing special about functions that you pass to other functions. The only reason they're often written inline is because they aren't needed except in that one place, so there's little point in naming them separately.

// Named function
function add(num1, num2) {
    return num1 + num2;
}
// Anonymous function assigned to variable
var multiply = function(num1, num2) {
    return num1 * num2;
}

output += flexible(add, 3, 5);
output += flexibble(multiply, 3, 5);
Barmar
  • 741,623
  • 53
  • 500
  • 612