Function returning a function in JavaScript

Let's say we have a function like this that returns a string:

function func() { return '!'; } let result = func(); console.log(result); // shows '!'

Let's now instead of a string, by analogy, return an anonymous function:

function func() { return function() { return '!'; }; } let result = func(); // there will be a function in the variable result console.log(result); // shows 'function() {return '!';}'

As you can see, the variable result is now a function. Let's display the result of its work in the console. To do this, write parentheses to it:

function func() { return function() { return '!'; }; } let result = func(); console.log( result() ); // shows '!'

Since calling func() returns a function, we can immediately invoke this returned function, like this: func()() - the first parentheses get the result of the function func (which is a function itself), and the second parentheses are applied to the result of func.

Let's try:

function func() { return function() { return '!'; }; } console.log( func()() ); // shows '!'

Make the function func1 which, when called like this: func1()(), will return the number 1. Make a similar function func2 returning the number 2. Find the sum of the results of these functions.

Any nesting level

There may be also such function calls: func()()() and func()()() - and so on ad infinitum.

To do this, you need the inner function to also return a function, that one - another one, and so on. Here is an example:

function func() { return function() { return function() { return '!'; }; }; } console.log( func()()() ); // shows '!'

Make the function func that, when called like this: func()()()()(), will return '!'.

Parameters

You can pass parameters to the function calls we have studied. In the following example, the inner function expects a string as a parameter and prints it to the console:

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

The second bracket corresponds to the internal function when called, which means that we pass the desired string to this second bracket:

function func() { return function(str) { return str; }; } console.log( func()('!') ); // shows '!'

Let's make both the first function take a parameter and the second one. And the result of the call will be the sum of these parameters:

function func(num1) { return function(num2) { return num1 + num2; }; } console.log( func(1)(2) ); // shows 3

Make the function func, which, when called like this: func(2)(3)(4), will return the sum of the numbers passed to the parameters.

Make the function func, which, when called like this: func(2)(3)(4)(5)(), will return an array of the numbers passed in the parameters.

enru