Skip to main content

Posts

Showing posts from December, 2012

JavaScript Self-Executing Anonymous Functions Simplified

I've seen code like this everywhere, and maybe you have too. A function (hopefully wrapped in parenthesis) followed by some variables in parenthesis. (function(a, $){ ... code ... })(window, jQuery); I eventually started trying to research what they were, how they worked, and why they should be used. Most of the explanations got thick quick, so I thought I'd simplify things. In essence, this is declaring and calling a function all at the same time. The easiest way to think of it (for me, anyway) is that this: (function(a, $){ ... code ... })(window, jQuery); ...is roughly equivalent to this: var myFunction = function(window, $){ ... code ... } myFunction(window, jQuery); There are some (pretty big) differences (such as when and how it runs), but this is enough to get you started. The parenthesis wrapping the function aren't required, but are considered best practice and common courtesy because they help to identify t