Neat little example of a useful JavaScript closure

I just picked up the 5th edition of David Flanagan’s JavaScript, the Definitive Guide. I find it amusing that that book is the only JavaScript book officially recommended at comp.lang.javascript.

Closures are a powerful feature of JavaScript. However it’s often hard to explain in a few words, just what is useful about closures. Well, here on page 131 of the Rhino book, is the recipe for a unique ID generator that doesn’t require a global counter.

One thing that I personally enjoy about the Flanagan book is that he says things like “don’t pollute the global namespace.” :) This technique does not pollute the global namespace.

var uid = (
  function(){
    var id=0;
    return function(){
      return id++ ;
    };
  }
)();
//then just say:
alert(uid());

var uid = (function(){var id=0; return function(){return id++ ;};})();

One Response to “Neat little example of a useful JavaScript closure”

  1. Meme Washer Says:

    How to code anything in JavaScript

    This began as a post for the JAG internal wiki. But I wound up looking up a lot of good links, so I thought I’d mirror it. Basically this is an exhortation to use comp.lang.javascript…

Leave a Reply

You must be logged in to post a comment.