PineNuts0
PineNuts0

Reputation: 5234

JavaScript: Accept Division Function as Argument Into Another Function That Returns New Function --> Returns Quotient

I have a function that divides two input arguments:

const divide = (x, y) => {
    return x / y;
  };

I have a second function that takes the divide function as its input argument and returns a new function.

function test(func) {

    return function(){
        return func(); 
    }
}

const retFunction = test(divide);
retFunction(24, 3)

I am expecting the returned value to be 8 (24 / 3). But I'm getting a returned output of 'NaN'. What am I doing wrong?

Upvotes: 5

Views: 371

Answers (1)

KevBot
KevBot

Reputation: 18908

You need to pass the possible arguments to the function: ...args:

const divide = (x, y) => {
  return x / y;
};

function test(func) {
  return function(...args) {
    return func(...args);
  }
}

const retFunction = test(divide);
const result = retFunction(24, 3);
console.log(result);

Upvotes: 8

Related Questions