At first, it was mysterious and stylish, then it became regular, and now it’s just mundane! The usage of “self-invoking anonymous functions” is what I’m talking about. You know what I mean; it’s this:

    // I'm cool

Recently, I even managed to convince my poor brain that using many of these constructs amounted to maintainable and cool-looking code. I even thought that this:

function Constructor() {
Constructor.prototype.fn = function(){};

… was ugly enough to require a bit of self-invoking cool’ness:

var Constructor = (function(){
    function Constructor() {
    Constructor.prototype.fn = function(){};
    return Constructor;

What was I thinking?? … Well, I’ll tell you: I was trying to create the illusion of containment! I didn’t want the fn method declaration to be left astray, departed from its parent (the constructor).

When used in this way, the Self Invoking… cool’ness creates an entirely pointless closure, that only serves to comfort the human programmer. Its similar to this:

var fruits = "banana apple orange grape strawberry".split(' ');

Compared with the less-cool more-logical version:

var fruits = ['banana', 'apple', 'orange', 'grape', 'strawberry'];

So, they both end up exactly the same, but the former takes a while longer to actually produce the array upon interpretation. So, why exactly do we do this?

I know why I do it: it’s because I’m lazy; so lazy that I can’t even bring myself to type out an array of strings, even though doing so would result in a faster run-time! The cost of repeatedly reaching for the awkwardly placed ' or " on my keyboard, to type out the array, is obviously just too much for me to bare!

Maybe you don’t do it… but it is out there!

// From jQuery 1.3.2

Let’s compare that to the typed out array:


By typing it out the former “cool” way we save a total of ONE character! Worth it?

Do you have any “anti-patterns in the making” to share?

Note: Obviously, there are situations where a self-invoking cool’ness (what I will call them from now on) might be useful. For example, the module pattern, or that ol’ (function($){})(jQuery); trick.

Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!