Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

! preceding function in javascript? [duplicate]

Tags:

javascript

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?

like image 361
rg88 Avatar asked Mar 24 '11 16:03

rg88


3 Answers

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 
like image 110
Mike Lewis Avatar answered Sep 20 '22 03:09

Mike Lewis


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

like image 26
ThiefMaster Avatar answered Sep 24 '22 03:09

ThiefMaster


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

like image 30
Ming-Tang Avatar answered Sep 22 '22 03:09

Ming-Tang