1

I am fairly new to Javascript and I have picked up a codebase in which I see the following snippet:

if (DEBUG == false) { // WHAT S ALL THIS?!!
    while ((request = UrlS.pop()) != null) {
      (function() {
        var counterDB = (function() {
          var id = 0;
          return function() {
            return id++;
          }; // Return and increment
        })();
        var tw = items[num];
        console.log("Request " + request);
        getFeed(request, tw, httpRequestCallback, counterDB);
      })();
    }
  } else { // WHAT S ALL THIS?!! #2
    (function() {
      var counterDB = (function() {
        var id = 0;
        return function() {
          return id++;
        }; // Return and increment
      })();
      var tw = items[num];
      request = UrlS.pop();
      getFeed(request, tw, httpRequestCallback, counterDB);
    })();
  }

Especially around the counterDB var, what is the point of creating so many nested anonymous functions?

with a quick search, i found that it is used elsewhere for a check: `

if(counterDB()<maximumSolutions)`

why all this? why not just CurrentModule.increment() or smth?

Orkun
  • 6,998
  • 8
  • 56
  • 103
  • 2
    see: [What is the (function() { } )() construct in javascript?](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – charlietfl Jan 05 '15 at 09:48
  • 1
    Those inner IEFEs are quite pointless, the outer one (the loop body) would be required to get different `id` variable with different `counterDB` functions in the loop. – Bergi Jan 05 '15 at 09:53
  • from the ref question of @charlietfl: "This pattern is often used when trying to avoid polluting the global namespace " cool! but is this it? – Orkun Jan 05 '15 at 09:54
  • @Bergi i m afraid i didnT get it. could you elaborate with an answer pls? – Orkun Jan 05 '15 at 09:56
  • Bergi is saying that the counterDB function is always going to return the same value because it's being reinitialized with every loop. However @Bergi `getFeed` could be callling that function multiple times? – Ruan Mendes Jan 05 '15 at 19:15

1 Answers1

1

The IIFE assigned to variable counterDB closes variable id within it. It is a way by which you make variable id private to that IIFE. By doing this you make variable id accessible only from within IIFE. And that is why the function returned by IIFE can increment(or change) its value.

This will also avoid global namespace pollution since variable id is not accessible outside and thus no other function or stmt can change its value (which can happen by mistake).

Kelsadita
  • 1,038
  • 8
  • 21