Question

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?

Was it helpful?

Solution

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(){ }(); 

OTHER TIPS

Because if you don't do something then it looks like a syntax error:

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

Try it.

It's necessary to get the parser to a point where it expects an expression, so that the function keyword is recognized in that context. Otherwise, when the parser sees function as the first token in a statement, it expects a simple function declaration, and that can't be followed by a parenthesized argument list.

There are various alternatives, around each of which cluster various opinions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top