JavaScript Function Result

A function can return a result. To do this, use the return statement, after which the return value is indicated:

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

In this case, the function sum()takes two parameters and returns their sum. The return statement is followed by the return value. In this case, it is the value of the constant result.

After receiving the result of the function, we can assign it to some other variable or constant:

 
function sum (a, b) {
  return a + b;
}
let num1 = sum(2, 4);
console log(num1); // 6

const num2 = sum(6, 34);
console log(num2); // 40

Returning a function from a function

One function can return another function:

function menu(n){
 
    if(n==1) return function(x, y){ return x + y;}
    else if(n==2) return function(x, y){ return x - y;}
    else if(n==3) return function(x, y){ return x * y;}
    return function(){ return 0;}
}

const action = menu(1);         // select the first item - addition
const result = action(2, 5);    // execute the function and get the result into the result constant
console.log(result);            // 7

In this case, the function menu(), depending on the value passed to it, returns one of three functions or an empty function that simply returns the number 0.

Next, we call the menu function and get the result of this function – another function into the action constant.

const action = menu(1);

That is, here it action will represent a function that takes two parameters and returns a number. Then, through the name of the constant, we can call this function and get its result into the result constant:

 
const result = action(2, 5);

Similarly, we can get another return function:

function menu(n){
 
    if(n==1) return function(x, y){ return x + y;}
    else if(n==2) return function(x, y){ return x - y;}
    else if(n==3) return function(x, y){ return x * y;}
    return function(){ return 0;};
}

let action = menu(1);
console.log(action(2, 5)); // 7

action = menu(2);
console.log(action(2, 5)); // -3

action = menu(3);
console.log(action(2, 5)); // ten

action = menu(190);
console.log(action(2, 5)); // 0