Possible Duplicate:
What does the exclamation mark do before the function?
I’ve long used the following for self-executing, anonymous functions in JavaScript:
(function () { /* magic happens */ })()
Lately, I’ve started seeing more instances of the following pattern (e.g., in Bootstrap):
!function () { /* presumably the same magic happens */ }()
Anyone know what the advantage is of the second pattern? Or, is it just a stylistic preference?
These two different techniques have a functional difference as well as a difference in appearance. The potential advantages of one technique over the other will be due to these differences.
Concision
Javascript is a language where concision can be very important, because Javascript is downloaded when the page loads. That means that the more concise the Javascript, the faster the download time. For this reason, there are Javascript minifiers and obfuscators that compress the Javascript files to optimize the download time. For example, the spaces in
alert ( "Hi" ) ;would be optimized toalert("Hi");.Keeping this in mind, compare these two patterns
(function(){})()16 characters!function(){}()15 charactersThis is a micro-optimization at best, so I don’t find this a particularly compelling argument unless you are doing a code golf contest.
Negating the returned value
Compare the result value of
aandb.Since the
afunction does not return anything,awill beundefined. Since the negation ofundefinedistrue,bwill evaluate totrue. This is an advantage to people who either want to negate the returned value of the function or have an everything-must-return-a-non-null-or-undefined-value fetish. You can see an explanation for how this works on this other Stack Overflow question.I hope that this helps you understand the rationale behind this function declaration that would typically be considered an anti-pattern.