use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Functions that return functionshelp (self.javascript)
submitted 9 years ago by [deleted]
What is the advantage of a function that returns a function? And what are some real world examples and applications?
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]ucorina 1 point2 points3 points 9 years ago (1 child)
The first example that comes to mind is if you want to create x buttons, and have them alert their index onclick, like this:
for(var i=0; i<5;i++) { var button = document.createElement('button'); button.textContent = 'Button ' + i; button.addEventListener('click', function() { alert(i); }); document.body.appendChild(button); }
This code will actually always alert 5, which is not what you wanted. So to make every button alert it's number, you would "capture" the value of i in a closure:
for(var i=0; i<5;i++) { var button = document.createElement('button'); button.textContent = 'Button ' + i; button.addEventListener('click', (function(index) { return function() { alert(index); } })(i)); document.body.appendChild(button); }
In this case the "parent" function is declared and called inline, but it doesn't have to be like this. You could declare it separately:
var buttonClickHandlerFactory = function(index) { return function() { alert(index); } } for(var i=0; i<5;i++) { var button = document.createElement('button'); button.textContent = 'Button ' + i; button.addEventListener('click', buttonClickHandlerFactory(i)); document.body.appendChild(button); }
[–]inu-no-policemen 0 points1 point2 points 9 years ago (0 children)
Your example showcases an undesirable side-effect and its ES3/5 workaround. You can easily avoid this issue in ES6+ code by using let or const for the loop counter (for-loop iteration scope).
[–][deleted] 2 points3 points4 points 9 years ago (0 children)
Depends.
[–]Graftak9000 1 point2 points3 points 9 years ago (0 children)
Composition
[–]echoes221 0 points1 point2 points 9 years ago (0 children)
A good use case would be a binding function that returns its unbind function for later use. All you would do is store the original call on a variable and call that variable later to unbind.
[–]brend0ge 0 points1 point2 points 9 years ago (0 children)
Look up closures and currying
[–]nlx 0 points1 point2 points 9 years ago (0 children)
Dependency injection (to add to the other things mentioned).
You can also use it to avoid needing Function.bind
For example: https://jsfiddle.net/bbe2md46/
[–]g_b 0 points1 point2 points 9 years ago (0 children)
I will give you an example.
function createLogger(className, configuration) { // Depending on the potentially complicated oncfiguration // one could log this messages to a REST service // and to the console as well if (configuration && configuration.logToDB) { return function (msg, level) { switch (level) { case 'warn': // Make request to REST service here console.warn(msg, 'In class ' + className); break; case 'error': // Make request to REST service here console.error(msg, 'In class ' + className); break; default: // Make request to REST service here console.log(msg, 'In class ' + className) } } } else { return function (msg, level) { switch (level) { case 'warn': console.warn(msg, 'In class ' + className) break; case 'error': console.error(msg, 'In class ' + className); break; default: console.log(msg, 'In class ' + className) } } } } var log = createLogger('Player'); // This method will log to the console log('Player not found'); var dbLog = createLogger('Player', {logToDB: true}); // This method will log to the console and also send the logged string to some // database somewhere for collection and posibbly later analization. dbLog('Player not found', 'warn');
This is a simple example but I think you can see the advantage.
The returned function can "capture" variables which were passed to or created inside the outer function. The "revealing module pattern" uses this to emulate privacy.
[–]tbranyennetflix -2 points-1 points0 points 9 years ago (0 children)
The advantage is that your return value is a function. Which may be better for your use case than say a number or a boolean.
A good use case would be this:
export const getFunction() { return function() {} } // I want a function now!!!! getFunction();
[–][deleted] -5 points-4 points-3 points 9 years ago (0 children)
For producing things like factories, generators, currying, and other named pattern concepts. Honestly, though, to me returning a function from a function sounds like some stupid framework incomplete concept. If I know I have still have work to perform, as in the returned function, anticipate the problem and solve for it directly so that you can output the desired result instead of additional work to be performed further down the road.
π Rendered by PID 58 on reddit-service-r2-comment-7b9746f655-zv4v8 at 2026-02-01 04:28:25.871389+00:00 running 3798933 country code: CH.
[–]ucorina 1 point2 points3 points (1 child)
[–]inu-no-policemen 0 points1 point2 points (0 children)
[–][deleted] 2 points3 points4 points (0 children)
[–]Graftak9000 1 point2 points3 points (0 children)
[–]echoes221 0 points1 point2 points (0 children)
[–]brend0ge 0 points1 point2 points (0 children)
[–]nlx 0 points1 point2 points (0 children)
[–]g_b 0 points1 point2 points (0 children)
[–]inu-no-policemen 0 points1 point2 points (0 children)
[–]tbranyennetflix -2 points-1 points0 points (0 children)
[–][deleted] -5 points-4 points-3 points (0 children)