How Self-Executing Anonymous Functions Work

In my recent post on creating a jQueryUI widget, I referenced the concept of self-executing anonymous functions. I’ve actually had a few questions come up at the office lately about how they work, so I figured turning it into a blog post might not be a bad idea. It’s an important concept in Javascript many don’t know about. Others know how to use them, but don’t really understand how or why they work. Today I’ll cover step-by-step how to go from a traditional function to a self-executing anonymous function; hopefully it will be clear at the end how these things work.

To see how we get to a self-executing anonymous function, we can take some simple steps.  Let’s use the following simple block of Javascript for our example.

var test = "a";

function testFunc(foo) {
  alert(foo);
}

testFunc(test);

Since functions in Javascript are objects like any other, we can use operators on the object such as the ( and ) grouping operators.

var test = "a";

function testFunc(foo) {
  alert(foo);
}

(testFunc)(test);

Groovy.  But since we are running the function as soon as we create it, couldn’t we combine it into one statement and the function run itself?  Obviously we can or this article would have been a short-and-sweet “you can’t do it” so…

var test = "a";

(function testFunc(foo) {
  alert(foo);
})(test);

Just because the function hasn’t been assigned to the name testFunc yet doesn’t mean that it’s not already an object. And being an object, of the type function, means we can run it.  Now, it’s a simple step of saying “I don’t need to reference this function again–I want it to run and then forget about the function itself.  Great, functions in javascript can be anonymous so there’s no need to assign it a name:

var test = "a";

(function(foo) {
  alert(foo);
})(test);

I’d give a Steve Jobs’ style BOOM! but I’m just not sure it’s quite that big.  What I do know is that these little beauties are great for encapsulating functionality and keeping things out of the global namespace.  Take a look at the source code of jQuery and you’ll see that the whole library is wrapped in a single, self-executing function that is assigned to the jQuery global object. It’s precisely the reason that jQuery doesn’t pollute the global namespace nearly as much as other libraries.  

  • http://silentconversation.com jasonmcleod

    I think you’re missing the last ) on line 5

    I’ve never written one of these but after getting an error testing your example code I added the ) and it works like a charm!

    Thanks for the explanation!

  • http://briancrescimanno.com Brian

    Good catch! Silly typos!

  • http://maciekzych.com pgn

    wow. simple and informative!
    Exactly this is what I was searching for :)

  • http://codeniche.com.s99807.gridserver.com/?p=5 Basic Javascript MVC pattern

    [...] controller code is wrapped in a self executing anonymous function so that once the controller file is included the event listeners will be applied to the page. This [...]

  • http://www.andytimney.com/?p=127 Javascript self executing anonymous functions « Andy Timney

    [...] can use self executing anonymous functions to wrap up functionality and have private functions and [...]

  • http://www.driverbull.com/2010/12/self-executing-anonymous-functions-in-javascript/ 冬天挖煤的牛司机 » Blog Archive » Self-Executing Anonymous Functions in Javascript

    [...] 这篇文章牛司机主要是参考了Brian Crescimanno的blog,几个例子,简单明了。 [...]

  • John

    Wow, great examples. Thanks for this.

  • Nikhil

    Useful!

  • http://andytimney.wordpress.com/2010/10/26/javascript-self-executing-anonymous-functions/ Javascript self executing anonymous functions « $('random').blog()

    [...] can use self executing anonymous functions to wrap up functionality and have private functions and [...]

  • http://www.sitepoint.com/forums/javascript-15/variable-visibility-768649.html#post4912104 Variable visibility – SitePoint Forums

    [...] permalink Variables can't be declared without the var keyword. I'm not sure what you're asking then. See, you can declare & define a variable outside of the SEAF and then use it within the function, but you wont be able to get that value outside of the function. Check this out for some great info on self-executing anonymous functions: How Self-Executing Anonymous Functions Work | Brian Crescimanno [...]

  • Anon

    The function line should be prefixed with ; in case the programmer doesn’t terminate lines with semicolons.nnvar test = “a”nn;(function testFunc(foo) {n alert(foo);n})(test);n

  • Nick Brook

    Thanks. Was looking for a succinct answer to my “what on earth is this syntax” question :-)

  • Rob

    Very nicely explained. A perfect example of how less is more! Works great with my JavaScript library. Thanks.

  • http://thejoecode.com/2011/10/14/helpful-links-to-get-started-with-javascript/ Helpful links to get started with JavaScript « The Joe Code
  • Ml78

    I dont get how the (function)(argument) bit is working :S

  • http://briancrescimanno.com/ Brian Crescimanno

    That’s a stylistic suggestion and fully depends on the codebase in which your code will be running. In a well-managed and reviewed codebase with automatic builds and verification, “hacks” like this shouldn’t be necessary.

  • http://briancrescimanno.com/ Brian Crescimanno

    When a function is created via a function expression, it automatically returns a reference to itself (a function object). By wrapping the function expression in ( ), you say, “execute this function expression and use the return value in this position.

    It’s completely analogous to: 

    (a – b) + c;

    The second ( ) simply instructs the interpreter “execute this object as a function.”

  • http://www.abdullahyahya.com/2012/01/05/javascript-self-executing-anonymous-functions/ Javascript: Self-Executing Anonymous Functions « Abdullah Yahya

    [...] Another benefit is it doesn’t pollute the global namespace by not overriding other functions. To learn more, visit http://briancrescimanno.com/2009/09/24/how-self-executing-anonymous-functions-work/  [...]

  • Darren Schreiber

    I am wondering if you know the implications on memory and performance using this style. I don’t know any posts that explicitly detail that. Presumably the function, being unassigned, will be destroyed after it’s one-time use. Is that correct? Therefore this strategy is almost more efficient on memory usage (though possibly less on performance as garbage collection needs to clean it up?)

    Just thinking out loud…

  • rob

    I rarely comment on programming blogs, but this short article is excellent. 

  • Neill

    Thanks for a brilliantly simple and by the end of it ‘doh! of course!’ explanation.