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?

Community
  • 1
  • 1
rg88
  • 20,742
  • 18
  • 76
  • 110

3 Answers3

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
Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
  • 38
    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. – michelpm Jun 08 '13 at 18:29
  • I actually think "unparseable" is accurate - the js vm will not parse the first example. – Gershom Maes Feb 19 '20 at 20:59
  • @JeffHykin Your comment is interesting and entertaining. I will, however, point out that it should say "unary" ;) – valid Dec 05 '20 at 22:13
  • 1
    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. – Jeff Hykin Dec 07 '20 at 11:43
  • Wow that's embarrassing on my part, thank you @[valid](https://stackoverflow.com/users/1467307/valid). It's a shame Stack Overflow doesn't let comments be edited after 5 min. That one was worth deleting and fixing. – Jeff Hykin Dec 07 '20 at 11:47
14

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

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    That may be the motivation. But the resulting expression still behaves as any expression with `!` does. – Matthew Flaschen Mar 24 '11 at 17:00
  • 5
    @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. – Matthew Crumley Mar 24 '11 at 17:05
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

Ming-Tang
  • 17,410
  • 8
  • 38
  • 76