Skip to content

Instantly share code, notes, and snippets.

@latentflip
Created November 4, 2013 15:55
Show Gist options
  • Save latentflip/7304680 to your computer and use it in GitHub Desktop.
Save latentflip/7304680 to your computer and use it in GitHub Desktop.
(function ($) { … })(jQuery);

Yeah seriously what the funk is going on here? It looks freaky, but it's not so bad. Let's break it down:

What about if it was

(function(a) { console.log(a) })("Hello");

What would that do? Well the first parentheses are just defining a function, that takes an argument a, and console.log's it. Much like the brackets in (1+2) we can kind of ignore them.

The second set of brackets, is calling the function returned from the first set, passing in the single argument, "Hello". So this code would print "Hello" in the console.

You could rewrite that code as:

var myFunction = function(a) { console.log(a) }
myFunction("Hello");

If you wanted to use two lines and a local variable instead of one (with the caveat that you've now also polluted the global namespace with a myFunction variable.

We need the extra set of brackets around the function definition to allow us to call it immediately, otherwise JavaScript will complain.


So back to

(function ($) { … })(jQuery);

I was going to write more, but try reading this first: http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment