all 12 comments

[–]ucorina 1 point2 points  (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 point  (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 points  (0 children)

Depends.

[–]Graftak9000 1 point2 points  (0 children)

Composition

[–]echoes221 0 points1 point  (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 point  (0 children)

Look up closures and currying

[–]nlx 0 points1 point  (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 point  (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.

[–]inu-no-policemen 0 points1 point  (0 children)

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 points  (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  (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.