4

I was looking at Twitter's embedded code and saw that they are using !function. While I know that this evaluates to false, I was wondering what the point of it was.

Here is the code I am referring to:

!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
Ivan
  • 10,052
  • 12
  • 47
  • 78
samccone
  • 10,746
  • 7
  • 43
  • 50
  • 2
    possible duplicate of [What does the exclamation mark do before the function?](http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function) – pimvdb Jan 04 '12 at 15:51
  • 1
    nah ... I know what it does ... I want to know *why* they are doing it – samccone Jan 04 '12 at 15:52
  • 2
    The second answer there explains why. Granted, the title of the question is a bit unfortunate. – pimvdb Jan 04 '12 at 15:53

1 Answers1

6

It's to save a byte. It's the shortest way to invoke the function. The alternative would have been:

(function(){...})();

Note the syntax Twitter uses:

!function(){...}(params);

Which means that they have decreased the length to invoke a function by one byte.

EDIT: Just an after thought: It also makes it very clear that you are invoking the anonymous function.

Ivan
  • 10,052
  • 12
  • 47
  • 78
  • if that is so... !function(){ console.log("foo") } would log foo .. but it does not – samccone Jan 04 '12 at 16:33
  • See my edit, `!function(){console.log("foo")}();` should work. – Ivan Jan 04 '12 at 16:35
  • Wow, I wouldn't have guessed that. Do you know why it no longer requires parentheses? –  Jan 04 '12 at 16:52
  • @skier88: The reason why it works is described fully as the second answer to this question: http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function . – Ivan Jan 04 '12 at 16:55
  • Thanks. I was actually just reading that, and it kind of dodges the issue (though it explains everything I already know pretty well :p ). Maybe a better way of asking would be, why doesn't `function() {}();` work? –  Jan 04 '12 at 17:01
  • Actually, never mind, one of the comments on that post answered it. Apparently javascript parsers mistake it for a function declaration if it's the first thing on a line. –  Jan 04 '12 at 17:06