[ACCEPTED]-what does !function in Javascript mean?-javascript

Accepted answer
Score: 47

It is short-hand or alternative of self-invoking anonymous function:

  // code

Can 8 be written:

  // code

You can also use + instead of 7 !.

If you simply did:

  // code

That will create problems, that's 6 why you need to add ! before it which turns 5 the function declaration into function expression.

Quoting docs, section 12.4:

An ExpressionStatement cannot 4 start with the function keyword because that 3 might make it ambiguous with a FunctionDeclaration.

To 2 better understand the concept, you should 1 check out:

Score: 3

they're negating the result, not the function 6 itself:

!function( x ){ return x }( true );

In reality, it's a slightly compressed 5 form of:


since it requires 1 less character. The 4 reason it's needed is that you can't call 3 a function declaration directly, e.g. this 2 is invalid:


but adding the ! at the beginning 1 turns it into a function expression and makes it work.

Score: 3

It's usually used to work around a quirk 6 in the JavaScript syntax. This gives a syntax 5 error:

function() {

It's read as a function declaration 4 (like function foo () {}), rather than a function expression. So 3 adding the ! before it, or wrapping it in 2 parentheses, forces the parser to understand 1 that it's an expression.

More Related questions