Skip to content

Instantly share code, notes, and snippets.

@fideloper
Created April 13, 2012 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fideloper/2377043 to your computer and use it in GitHub Desktop.
Save fideloper/2377043 to your computer and use it in GitHub Desktop.
More fun Javascript enclosures
Instead of the "traditional":
(function() {
})();
You can do:
!function(){
//I saved some characters, and now I'm trendy.
}();
Or:
+function(){
//If you're a hipster and just can't be like everybody else (scoff, so main stream), the '+' means better.
}();
@CMCDragonkai
Copy link

Interesting, why does this work?

@andergmartins
Copy link

Interesting :)

I think it works because the parenthesis, !, + and - signs force the JavaScript parser/engine treat the following entity (in this case the function declaration followed by the (), which return a value ) as on object, because those signs start an expression and it will make the parser use the returned value from that function as the second term on the expression. Testing it on the console you can see that it will return a value.
The traditional way returns undefined, but the others will return a boolean or NaN value.

On the simple function declaration the following () whould break the syntax, this is way it requires those signs before.

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