Open In App

How to call a function that return another function in JavaScript ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The task is to call a function that returns another function with the help of JavaScript is called a Currying function, a function with numerous arguments that can be converted into a series of nesting functions with the help of the currying method.

Approach:

  1. Define Outer Function:
    • Create an outer function that takes parameters and contains the logic for processing or initializing data.
  2. Return Inner Function:
    • Inside the outer function, return another function (inner function). This inner function can access variables and parameters from the outer function due to closure.
  3. Call Outer Function:
    • Call the outer function to obtain the inner function. Assign the result to a variable if needed.
  4. Invoke Inner Function:
    • Call the returned inner function separately, either immediately or at a later point in your code.

Example 1: In this example, “from function 2” is returned from the fun2 which is finally returned by fun1

Javascript




function fun1() {
    function fun2() {
        return "From function fun2";
    }
    return fun2();
}
 
function GFG_Fun() {
    console.log(fun1());
}
GFG_Fun()


Output

From function fun2

Example 2: In this example, “Alert from fun2” is returned from the fun2 along with an alert, Returned value is finally returned by fun1

Javascript




function fun1() {
    function fun2() {
        console.log("From function fun2");
        return "Alert from fun2 ";
    }
    return fun2();
}
 
function GFG_Fun() {
    console.log(fun1());
}
GFG_Fun()


Output

From function fun2
Alert from fun2 



Last Updated : 11 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads