Possible Duplicate:
What does the exclamation mark do before the function?
I’m maintaining an existing site with a “tweet” button, which appears to come from this page
A colleague here brought up a great question: Why does this script tag reverse the (undefined via no return statement) value of this self-calling function? (pretty-fied for ease of reading, original is at link)
<script>
!function(d,s,id) {
//^--- that
var js,fjs=d.getElementsByTagName(s)[0];
if(!d.getElementById(id)) {
js=d.createElement(s);
js.id=id;
js.src="https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js,fjs);
}
}(document,"script","twitter-wjs");
</script>
To my non-JS-pro eyes, that appears to be flipping the boolean value of undefined, thereby allowing the entire <script> tag to evaluate to true. For what it’s worth, that is a totally foreign idea to me (that <script> tag has an expression value).
My expectation is that there is some specific browser out there for which a <script> tag’s boolean value (yes, I feel crazy even typing that) matters.
So the basic question is this: Does a <script> have a meaningful “expression” value to any browsers you know of? and What is the implicit meaning of a true vs. false in this case?
An explanation of what is going on and why…
In Javascript, you have
function statementsandfunction expressions. The two of them are similar, but not exact.Function statement
Function Expressions
Updated due to comments
I prefer the first form because it lets me use the block matching tools on my editor, and the
f1form is preferred by the sometimes useful programs JSLint and JSHint.All create a function expression and then invoke it immediately. In this case, the parens are not needed by the Javascript compiler, but they serve as a very useful hint to the reader that this is not a normal assignment.
On the other hand, you must have something to tell the JS engine that you have a function expression instead of a function statement. The
=sign above works, but when there is no assignment, you need to start off with some kind of operator, be it(+!The leading operator makes it an expression. The
()in the above examples force it to an expression as well.