Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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.

like image 502
David Perlman Avatar asked Nov 25 '12 08:11

David Perlman


People also ask

What Is syntax in a formula?

Syntax refers to the structure and order of a formula, including functions, references, operators, and parameters.

What is the use of syntax in Excel?

A formula in Excel is used to do mathematical calculations. Formulas always start with the equal sign = typed in the cell, followed by your calculation.

What is the purpose of count () function?

The COUNT function counts the number of cells that contain numbers, and counts numbers within the list of arguments. Use the COUNT function to get the number of entries in a number field that is in a range or array of numbers.


1 Answers

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");
})();
like image 115
Paul Avatar answered Oct 28 '22 01:10

Paul