1

Did anyone know the code which define like this:

!function(window, undefined) {
    // do something
} (window)

By searching in google, I can understand the syntax like:

function(window, undefined) {
    // do something
} (window)

But I don't figure out any article about the syntax have "!" operator.

Martin Smith
  • 438,706
  • 87
  • 741
  • 845
Leonhart 27
  • 101
  • 3
  • 11

2 Answers2

3

The ! operator is there so the function is parsed as an expression, rather than a declaration. Since a declaration cannot be invoked, your second example is a syntax error.

A more commonly seen form is to enclose the function in parentheses:

(function(window,undefined) {
    // do something
}(window));

That has exactly the same effect, as does the use of any unary operator.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • I think you mean (function(window,undefined) { ... })(window); – francisco.preller Jun 03 '13 at 07:00
  • I just came by this thread and was curious. By expression you mean like i.e an if statement? `if (function()) {}`? – CaptainCarl Jun 03 '13 at 07:00
  • the exclamation mark transform the definition into an expression so that the parenthesis can call it right after because it has higher priority, `!function(){}()` is an evil version of `(function(){})()` – Frederik.L Jun 03 '13 at 07:04
0

It might be like this.

!(function(window, undefined){ /* some code */ })(window);
(function(window, undefined){ /* some code */ })(window);
Edward
  • 4,887
  • 3
  • 17
  • 25