-
-
Save rwaldron/760402 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment