0

I'm newbie in JS, and in this JS closure example

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();

I can't get why the variable add is assigned to the invocation of the function, not the function itself. In other words, now add is supposed to be referencing an invoked function, and to call add, we don't need to add () at the end, it is already called. Why does the example call it like this: add() ? I can't find the exact term for it, but isn't this like 'double calling' the function ?

andrew
  • 8,614
  • 7
  • 25
  • 56
a.u.r
  • 1,153
  • 2
  • 19
  • 32
  • Could you provide the code within the question itself? – evolutionxbox Apr 30 '16 at 15:40
  • 4
    _"assigned to the invocation of the function"_, no it is assigned the returned function expression `function () {return counter += 1;}` – Patrick Evans Apr 30 '16 at 15:41
  • And thanks to JS closures, the returned function has access to the live counter variable. This is one of the most powerful features of JS. – evolutionxbox Apr 30 '16 at 15:42
  • 1
    part of the issue is the function is miss named. it should be something like addFactory . because the add function is only returning an function that does adding. The example is doing this. var addfunc = add(); addfunc() // 1 addfunc() // 2 etc – adrianj98 Apr 30 '16 at 15:46
  • @PatrickEvans so the last '()' is there to return the enclosed function expression itself? – a.u.r Apr 30 '16 at 15:47
  • 1
    Possible duplicate of [How do JavaScript closures work?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Patrick Evans Apr 30 '16 at 15:54
  • 2
    Also definitely read this http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript – Wiktor Zychla Apr 30 '16 at 15:59

1 Answers1

0

take a look at this code

function createCounter(){
    var index = 0;  //initialize the index
    //returns a closure that increments the index, 
    //and returns the value on every invocation
    return function(){ return ++index; }
}

//crete an "instance" of a counter
var aCounter = createCounter();
//and invoke it a few times
console.log("a", aCounter());
console.log("a", aCounter());
console.log("a", aCounter());

//create another counter, and invoke it
var anotherCounter = createCounter();
console.log("b", anotherCounter());
console.log("b", anotherCounter());

//showing that they increment independent of each other
console.log("a", aCounter());
console.log("a", aCounter());

that would be a "good" implementation of this utility, because you can use it over and over again, without repeating yourself.

If you invoke createCounter directly, you get your code-example.

var aCounter = (function(){
    var index = 0;
    return function(){ return ++index }
})();
Thomas
  • 3,245
  • 1
  • 10
  • 8