David Perlman
David Perlman

Reputation: 1470

What does the syntax !function() { ... } mean?

I found this syntax in the simple, great, wonderful and powerful library knockoutjs:

!function(factory) { ... }

What is the meaning of the not sign (!) before the function declaration?

UPDATE: The source code no longer contains this exact syntax.

Upvotes: 5

Views: 129

Answers (1)

Paul
Paul

Reputation: 141917

The ! operator behaves as normal, negating the expression. In this case it is used to force the function to be a function expression instead of a function statement. Since the ! operator must be applied to an expression (it makes no sense to apply it to a statement, because statements don't have a value), the function will be interpreted as an expression.

This way it can be executed immediately.

function(){
    alert("foo");
}(); // error since this function is a statement, 
     // it doesn't return a function to execute

!function(){
    alert("foo");
}(); // This works, because we are executing the result of the expression
// We then negate the result. It is equivalent to:

!(function(){
    alert("foo");
}());

// A more popular way to achieve the same result is:
(function(){
    alert("foo");
})();

Upvotes: 9

Related Questions