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?
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
There are some benefits of function expressions over statements, for example they are anonymous functions, they can be used as closures, as arguments to other functions and as IIFEs. Put simply a statement in the execution phase it does not return anything, an expression results to a value, an object is created.
functions are data in memory stack, so when you define another function with the same name, it overrides the previous one. Show activity on this post. Well obviously you're not meant to define the same function twice. However, when you do, the latter definition is the only 1 that applies.
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.
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 to alert("Hi");
.
Keeping this in mind, compare these two patterns
(function(){})()
16 characters !function(){}()
15 characters This is a micro-optimization at best, so I don't find this a particularly compelling argument unless you are doing a code golf contest.
Compare the result value of a
and b
.
var a = (function(){})() var b = !function(){}()
Since the a
function does not return anything, a
will be undefined
. Since the negation of undefined
is true
, b
will evaluate to true
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With