Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
PineNuts0 Avatar asked May 24 '19 16:05

PineNuts0


People also ask

How do you do division in JavaScript?

Division (/)The division operator ( / ) produces the quotient of its operands where the left operand is the dividend and the right operand is the divisor.

What is function argument in JavaScript?

Function arguments are the real values passed to (and received by) the function.

Which of the following statements is the correct way to define a function in JavaScript?

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().


1 Answers

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);
like image 129
KevBot Avatar answered Sep 29 '22 19:09

KevBot