5

I was looking at the jQuery plugins for Twitter Bootstrap and saw that they were all defined using a pattern like this:

!function($) { // code here // plugin definition here } ( window.jQuery || window.ender); 

This looks like a variation of the immediately executing anonymous function (anonymous closure):

(function($) { // code here }(jQuery)); 

Can someone explain what the Bootstrap variation does and why? Is this a better way to write an anonymous closure?

Thanks!

4
  • 1
    I think the only difference is that it saves you a character... Oh, and makes the pattern obscure. Commented Jan 20, 2012 at 23:33
  • 2
    @Jordão: Avoiding the () helps avoid bugs like this one Commented Jan 20, 2012 at 23:42
  • @am not i am: thanks for pointing that out. I'd still not use this idiom though, as it's not the proper way to fix that kind of bug. Commented Jan 21, 2012 at 1:23
  • @Jordão: I wouldn't call it an improper fix. Irrespective of the bug, I still don't use () to create an IIFE. The bug is a combination of JS only having function scope, having ASI, and overloading the () syntax. It's up to the individual developer as to how they want to deal with it. Inserting a semi-colon is one option. Commented Jan 21, 2012 at 2:21

1 Answer 1

11
// |---1. makes the function as part of an expression // | so it can be immediately invoked // v !function($) { // ^ // |___4. references what was passed, window.jQuery or window.ender // code here // plugin definition here } ( window.jQuery || window.ender); // <---2. immediately invoke the function // ^ ^ // |________________|_______3. pass window.jQuery if it exists, // otherwise window.ender 
Sign up to request clarification or add additional context in comments.

8 Comments

Nice answer - thanks! So it looks like it really is another way of doing the same thing with the benefit of preventing bugs when the code is combined?
@ɹǝʇǝd: Yeah, if you forget a semicolon before this, the () may be interpreted as attempting to call a function.
What is window.ender? In which cases is it populated? I couldn't find much information, except for Bootstrap code of course.
Ender is an open module JavaScript framework. See ender.no.de for more information.
@mike: The concern is that the syntax is interpreted such that the function keyword is not seen as function declaration syntax, but rather as an anonymous function that is part of an expression. This allows the immediate invocation. Almost any operator can be used to accomplish this. The logical not operator is just one. Some people wrap the entire function in (), but bugs can crop up with this approach. If you remove the !, and don't use anything else to make it a function expression, then you'll get a SyntaxError because it'll be seen as a declaration with its name missing.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.