How to call a function that return another function in JavaScript ?
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:
- Define Outer Function:
- Create an outer function that takes parameters and contains the logic for processing or initializing data.
- 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.
- Call Outer Function:
- Call the outer function to obtain the inner function. Assign the result to a variable if needed.
- 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
Share your thoughts in the comments
Please Login to comment...