0

I've just come across the use of !function

Can anyone explain to me why this works? I've never seen any javascript use this code before, and it's a difficult thing to search.

> !function(world) { alert('Hello ' + world); }('World');
true
> function(world) { alert('Hello ' + world); }('World');
SyntaxError: Unexpected token (
> (function(world) { alert('Hello ' + world); })('World');
undefined
CaptainCasey
  • 1,311
  • 1
  • 14
  • 21
  • 2
    It forces the function to be interpreted as an expression, not a declaration. This has been asked before, I'll try to find it. – bfavaretto Apr 18 '13 at 00:45
  • 2
    See also [javascript function leading bang ! syntax](http://stackoverflow.com/questions/5827290/javascript-function-leading-bang-syntax) – apsillers Apr 18 '13 at 00:47
  • Bergi is right. That question already has the answer to my question. – CaptainCasey Apr 18 '13 at 00:51
  • Thanks @Bergi, I have been looking for that site, but forgot the name! – bfavaretto Apr 18 '13 at 00:52
  • Although that duplicate question exactly answers the specific question, see this answer for a further exploration into the subject: http://stackoverflow.com/questions/13965702/js-whats-the-difference-between-a-closure-and-closure/13965980#13965980 – slebetman Apr 18 '13 at 02:43

0 Answers0