Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created December 24, 2010 00:14
Show Gist options
  • Save cowboy/753725 to your computer and use it in GitHub Desktop.
Save cowboy/753725 to your computer and use it in GitHub Desktop.
A few variations on writing an IIFE
// Want to learn more about Immediately Invoked Function Expressions? Read
// this article first:
//
// http://benalman.com/news/2010/11/immediately-invoked-function-expression/
// Parens are used to tell the parser that it's a function expression,
// not a function declaration. If you don't explicitly tell the parser to
// expect an expression, it will throw a SyntaxError exception because it
// sees a function declaration without a name specified.
(function(){ /* code */ })() // I've been using this one
(function(){ /* code */ }()) // Crockford recommends this one
// If you don't care about the possible performance overhead of performing
// type coercion on the function's return value, you can save a byte by
// prefixing the function with a unary operator.
!function(){ /* code */ }()
~function(){ /* code */ }()
-function(){ /* code */ }()
+function(){ /* code */ }()
// Because the point of the parens or coercing operators is just to tell
// the parser to expect a function expression and not a declaration, they
// can be omitted when it already expects an expression.
var i = function(){ return 10; }();
condition && function(){ /* code */ }();
// Here's another variation, from @kuvos - I'm not sure of the performance
// implications of using the `new` keyword, but it works.
// http://twitter.com/kuvos/status/18209252090847232
new function(){ /* code */ }
new function(){ /* code */ }() // Only need parens if passing arguments
@cowboy
Copy link
Author

cowboy commented Dec 31, 2010

Thanks for the comment, Dmitri. I've actually just updated/rewritten my original article to reflect this and other changes I've wanted to make.

Check it out if you have any interest!
Immediately-Invoked Function Expression

@DmitrySoshnikov
Copy link

Yep, great; also I like an IIFE abbreviation. It's seems the most fitted naming IMO.

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