Why use NOT operator on anonymous function call? (a la Knockout 2.1.0)

CgodLEY picture CgodLEY · Aug 11, 2012 · Viewed 7.9k times · Source

Possible Duplicate:
What does the exclamation mark do before the function?

If you look at the source code for KnockoutJS 2.1.0 you will see a code structure like this start on line 7:

!function(factory) { ... }(factoryDefinition);

The not operator causes this expression to evaluate to true rather than undefined, but why bother?

Answer

Peter Olson picture Peter Olson · Aug 11, 2012

This is a concise way to form an immediately executed function expression.

Traditionally, people have used these two forms

(function(){ }()); // Recommended by Crockford
(function(){ })(); // What most people use

If you try to just use

function(){ }(); // Syntax error

it will be a syntax error, because it is interpreted as a function declaration rather than an expression. This is why you would need to wrap the function in parentheses.

But if you put a unary operator before the function declaration, you don't have to add a cosing parentheses, and it chops off one character of the code, which is a (very) tiny performance benefit. There are several unary operators that can be used for this same purpose

!function(){ }();
~function(){ }(); 
-function(){ }(); 
+function(){ }();