JavaScript Pills: function that returns another function

Lari Maza
Lari Maza | En
Published in
2 min readOct 7, 2019
Photo by TheThinkSomeMoreStore

[clique aqui para ler em português]

This is a post from a series where I share insights from my journey with JavaScript in a mini article format. See all other posts on my profile!

A function that returns another function is a type of higher order function. Observe the example below:

function outerFunction() {
alert('Hello!');
return function() {
alert('Can you hear me?');
};
}

Despite what it may seem, if we simply call the outer function with outerFunction(), we will only see the first alert 'Hello!'; the inner function code will not be executed. We’ll need a specific trick if we want to trigger the second alert!

There are two ways to execute the returned function. One option is storing the external function outerFunction in a variable. Behind the curtains, we are actually storing the return of the function this way:

const innerFunction = outerFunction();

Now, we can call this new variable like any other function and only the returned function will be executed:

innerFunction();
// alert 'Can you hear me?'

Another alternative is calling the function immediately, without the need to create a variable. Just add another set of parentheses to the external function call:

outerFunction()();
// alert 'Hello!' and then alert 'Can you hear me?'

Note that the effect in this case is different from the first example. Here, the first pair of parentheses executes the outerFunction function and returns the inner function, which is then called by the second pair of parentheses!

We must choose an approach by assessing whether or not we want to execute the external function content before the returned function content is executed.

That’s all for today and see you next time ❤

--

--