Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.
Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?
function counter() {
var _counter = 0;
function increase() { return _counter++ }
return increase;
}
// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
var createClosure = counter();
createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3