37

Possible Duplicate:
What does the exclamation mark do before the function?

I saw a function formatted like this today for the first time:

!function(){}(); 

What is the preceding exclamation mark for? I assume it functions the same as:

(function(){})(); 

But... what's going on here?

0

3 Answers 3

46

The preceding ! takes the un-parseable statement, and allows it to to be parsed by the JS engine, which in turn returns true.

function(){}(); SyntaxError: Unexpected token ( !function(){}(); >>true 
Sign up to request clarification or add additional context in comments.

5 Comments

This is so misleading, it doesn't make anything parseable, it makes a function declaration be parsed as an expression, that evaluates to the function itself, allowing it to be called.
I actually think "unparseable" is accurate - the js vm will not parse the first example.
@JeffHykin Your comment is interesting and entertaining. I will, however, point out that it should say "unary" ;)
To add some clarity (adding to @michelpm's point) both +function(){}(); and -function(){}(); also work because + and - can be unary operators. However ! is preferable since it is only a unary operator, while + and - can be both binary and unary operators.
Wow that's embarrassing on my part, thank you @valid. It's a shame Stack Overflow doesn't let comments be edited after 5 min. That one was worth deleting and fixing.
14

It simply makes the JavaScript parser parse it as an expression, which is necessary to execute it.

2 Comments

That may be the motivation. But the resulting expression still behaves as any expression with ! does.
@Matthew: I can't speak for gaoshan88, but it looks like he's interested in the motivation, since he compared it (correctly) to another common way of writing self-executing functions.
13

I've tried it, it returned true. The function returns undefined, and !undefined is true.

!function(){}(); ^ ^ ^ C A B 
  • A. function(){} is an empty anonymous function
  • B. () executes the function (A), returning undefined
  • C. ! negates undefined, which becomes true

I think they used that trick for a code golf or an obfuscated code. It is a bad practice to practially use that

Try javascript:alert(!function(){}()) in your browser address bar

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.