Ask JW: Decoding Self-Invoking Anonymous Functions

Between Nettuts+ and ThemeForest,
I receive dozens of question emails each week. Although I try my best, I simply don’t have the time to research the answer to each one. Considering this, I’ve decided to sporadically post “Ask JW” articles. This week’s question concerns Javascript’s self-invoking anonymous functions, and comes from Travis.

The Question

“Hi, Jeffrey. I love your “jQuery For Absolute Beginners” series. It’s helped me so much!! Can you explain why I have to add all of that extra information around my function when I create a jQuery plugin? What’s it for, and why is “$” passed as a parameter?
– Travis

The Answer

Hey, Travis. I assume you’re referring to something like the following:

(function($) {
	$.fn.myPlugin = function(){};
})(jQuery);

We do this in our plugins to ensure that the dollar symbol does not conflict with any other Javascript libraries. What if you’re using jQuery and Protoype simultaneously? In such instances, the $ symbol refers to different things.

One possible remedy is to type ‘jQuery’ instead of ‘$’ each time – but this is inefficient and makes for quite ugly code. The solution is to pass ‘$’ as a parameter. That way, within the anonymous function, we have exclusive access to the symbol.

A Simple Example

My guess is that you’re not 100% sure exactly what a ’self-invoking anonymous function’ is. Let’s review a simple example. Consider the following function:

function doSomeAlert() {
 alert('Hello World');
}

As you might have guessed, this function won’t automatically run when the page loads. If we want it to, we need to call it.

doSomeAlert();

Easy enough. Is there any other way to make a function run when the page loads without calling it? Yes; to do so, we’ll wrap our function within parenthesis, and then append one more set – like so.

(
	function doSomething() {
		alert('Hello World');
	}
)();

Now, if you run this block of code in your browser, an alert will immediately be displayed.

Alert Box

How Come?

Notice that second set of parenthesis, just before the closing semi-colon? This set basically means, “Execute!”. We can simplify this code even further by turning our function into an anonymous one.

(
	function() {
		alert('Hello World');
	}
)();

Parameters

Now what if we wanted to pass a parameter to our anonymous function? We can accomplish this by passing it through the second set of parenthesis. Let’s revise the previous function so that it accepts a ‘name’ parameter.

(
	function(name) {
		alert('Hello ' + name);
	}
)('Jeffrey');

Notice how we passed ‘Jeffrey’ as a parameter? This value is then sent to our anonymous function!

Alert Box

Back to jQuery

Let’s refer back to Travis’ question. How can we pass the ‘$’ symbol without it interfering with other Javascript libraries? Let’s use the same method as we just learned.

(
	function($) {
		$.fn.myPlugin = function() {}
	}
)(jQuery);

Now, you should understand that we’re passing the jQuery object as a parameter, which will then be represented by ‘$’. It’s as easy as that!

What are the Benefits of Using Self-Invoking Anonymous Function?

There are plenty. We just demonstrated one usage. Another one would be to accomplish some work without having to create a bunch of global variables.

Additional Resource

If you’re still a bit weary about creating jQuery plugins, I recommend that you review the article and screencast found here.

Hope this answers your question!



17

Comments
  • Vasili says:

    I really learned about the self-invoking functions when I watched that screencast about jQuery on your site, Jeffery. :)

  • Meshach says:

    Very interesting.. :)

  • Next time on ask JW: Jeffrey finally explains the meaning of life and the universe and how he is taking over the world one tutorial at a time. Stay tuned. ;)

    Seriously though, this is a really unique idea Jeffrey, I think this will be beneficial to a lot of people, including me!

  • Tarek Farage says:

    Why is the sky blue? :P

    Nice one, looking forward to more of these!

  • Andres Fernandez says:

    Great idea with this series. Thanks for taking the time to do this.

  • Daniel says:

    thank you very much! i’m quite new to js and jquery but you explain very well jeffrey :)

  • Meshach says:

    @Drew: I laughed out loud (literally) when I saw your comment. haha

  • Saro says:

    I had to laugh with this ‘Ask Jeffrey’ thing :D , and even more with Drew.

  • Great article, very well written. Thanks!

  • Shingi says:

    This is awesome!! Love this series.

  • Tulsi says:

    This seems to be a good content. Appreciate it.

  • Thank was a very useful explanation. Thanks!

  • JimB says:

    Wow! I’ve been trying to teach myself jquery by reading other peoples’ code and “intuiting” what is going on based on my knowledge of old-school languages (VB, Pascal, etc.). I’m not sure how I ever would have gotten to the point where I saw the construct ( F(n){} ) (x) as “immediately execute function F passing the value of x into the parameter n”. There’s nothing like that in VB.

    You have explained so clearly that I can’t see how it could have been anything else.

    I am only part-way through the “jQuery for Beginners” series but have learned a ton. Is there some reference, though, that would help an old fogey like me learn how to _read_ javascript?

  • damon medic says:

    Great, tutorials, Jeffrey. You must have had a brilliant mother!

  • Alec says:

    I just had an Aha! moment :)

  • Rolf says:

    Indeed, an Aha! moment! :D

  • Alex says:

    Thanks! Didn’t realize JS allowed this (but not surprised I guess).

    Not digging the explanation as much as everyone else, though. I think the most important fact is omitted. In JS, the name of a function is just a name that points to a chunk of code. When you call a function named foo, like so:

    foo();

    …you are telling JS to execute the chunk of code that looks something like this:

    function foo(){…}

    There is virtually no difference (apparently) between calling the function by its name and inserting the entire chunk of code representing the function directly into the call statement. In other words, the following do the same thing:

    foo();
    (the_whole_function)();

    Why? Because foo = the_whole_function.

    Sorry, maybe for some people it seems like I am just reiterating. But this way of explaining it seems to me a lot more clear than saying parentheses cause the function execute…somehow.