I have different functions that run very simple mathematical equations. I want to have a function that is able to call any of these functions based on a variable that is set separately. I can't seem to get the function to recognize the variable as a "function" input.
When run in console, this gives me the result I'd expect:
function operate(whatOp, a, b){
console.log(whatOp(a, b)}
So typing...
operate(divide, 3, 4)
...in console returns 0.75.
Yet, if I try to call it by having whatOp come from a variable, it doesn't work as...
let firstNumber = "999";
let secondNumber = "333";
let operation = "divide";;
operate(operation, firstNumber, secondNumber)
...in console returns undefined.
How do I get it to work based on this? I'm using a button to set the variable, but that's working and returns the value I want, so I think it has to do with the way I'm calling the variable?
operationis expected to be afunctionthat accepts 2 arguments and not astring.let operation = divide. You ware passingdivide, in your working example, not"divide"divideis in e.g. window scope, thenoperate(window[operation], firstNumber, secondNumber)would work.divide