Incrementing Integers with ++

by Ian Roberts

JavaScript

function newCounter() {
    // return a counter that is incremented on call (starting at 0)
    // and which returns its new value
    var a = 0;
    var b = function() { a++; return a; };
    return b;
}
 
c = newCounter();
alert(c() + ' ' + c());  // outputs "1 2"

//other code...
//more instances of c();

//javascript remebers the queue of where the counter was last left off
alert(c() + ' ' + c());  // outputs "3 4"