I've seen:
!function(){ //code }();
Used in several places to immediately execute an anonymous function. Normally, it's used in lieu of:
(function(){ //code }())
Anyone know how the !
actually makes the function execute?
Since an array is passed as a pointer, the array's memory is not copied. The function uses the memory of the same array that is passed to it, and can change what is in that memory.
Duplicate declarations are simply an equivalent restatement of an interface specification, and that has no effect on code which depends on that interface.
What the ! does
When you use !
, the function becomes the single operand of the unary (logical) NOT operator.
This forces the function to be evaluated as an expression, which allows it to be invoked immediately inline.
Other alternatives
You can do this with just about any operator. Here are some examples...
'invoke',function(){ /*code*/ }();
1+function(){ /*code*/ }();
void function(){ /*code*/ }();
~function(){ /*code*/ }();
+function(){ /*code*/ }();
Nice thing about some of these is that the meaning of the operator is not overloaded.
The problem with ()
When you use ()
around the function, you can hit some bugs that will crop up if you have more than one in a row without a semicolon separating them.
(function() {
alert('first');
}())
(function() {
alert('second');
}())
// TypeError: undefined is not a function
This will result in a TypeError
, because the pair of outer ()
around the second function will be interpreted as intending to call a function. The first one doesn't return a function of course, so you're trying to call on undefined
.
How using a different operator copes with (or avoids) the problem
Even an operator like +
, which is overloaded to some degree won't cause an error.
If you do this...
+function() {
alert('first');
}()
+function() {
alert('second');
}()
The first +
is interpreted as a unary + operator, and it converts the result returned from the first function, which in this case is undefined
so it gets converted to NaN
.
The second +
will be interpreted as the addition operator, and so will try to add NaN
to the return result of the second function, which again here is undefined
.
The result of course is NaN
, but it is harmless. There's no illegal code to throw an error.
Demonstration of how the operators interact with the functions
To prove this, just give each function a return value, then paste it into the console...
+function() {
alert('first');
return "10";
}()
+function() {
alert('second');
return 20;
}()
// 30
You'll get the two alert
s, and then the console will show 30
because the first +
operator converts the String "10"
to the Number 10
, and the second +
added the two results together.
The !
is an ordinary logical negation.
The ()
executes the function.
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