18

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?

thedz
  • 5,496
  • 3
  • 25
  • 29
  • 1
    It's worth pointing out that while the former works, it does negate the value returned by the function, whereas the second form does not. – toddsundsted Dec 23 '11 at 02:46

2 Answers2

40

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 alerts, 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.

2

The ! is an ordinary logical negation.
The () executes the function.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 5
    I think OP is asking why simply prepending `!` to `function(){ //code }()` (which is otherwise an error) causes the anonymous function to be executed. – toddsundsted Dec 23 '11 at 02:42