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.

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I think you mean (function(window,undefined) { ... })(window);
I just came by this thread and was curious. By expression you mean like i.e an if statement? if (function()) {}?
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(){})()
0

It might be like this.

!(function(window, undefined){ /* some code */ })(window); (function(window, undefined){ /* some code */ })(window); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.