3 ms·
Well, when all is said in done, the statement the author makes is pretty much incorrect in every sense. `!function(){}()` is a type of immediately-invoked funct
by rmrfrmrf 12y ago
Well, when all is said in done, the statement the author makes is pretty much incorrect in every sense. `!function(){}()` is a type of immediately-invoked function expression. Even if the `!` weren't there, `function(){}` would still be a function expression (compare to `var fun = function(){};`, a function declaration).
Second, `!` in JavaScript does not convert a function declaration into a function expression; it invokes the NOT operation on whatever immediately follows it.
Examples:
> !true;
false
> !false;
true
> !4;
false
> !undefined;
true
> !!undefined;
false
So, basically what this code is doing is creating a function, calling it (with `()`), and then running a NOT operation on it.
I personally hate this kind of code because it's hacky and works by exploiting the interpreter. If you look at the examples of the `!` operator I gave, `!undefined` returns `true`, which is exactly what the author's code will return. Granted, the chances that you'll get bitten for using `!` over just a pair of parens is slim, you're still forcing the interpreter to waste [an incredibly small amount of] time performing useless operations just because the programmer was too lazy to type parentheses.
Much better, IMO, would be `(function() {})()` or, more safely and explicitly, `(function() {}).call(this)`, which sets the function expression's context to Window even in strict mode. `foo()` is syntactic sugar for `foo.call(undefined)` in strict mode and `foo.call(window)` in non-strict mode.
- wpears 12y agoYou mixed up your definitions of function declaration and function expression. In this case, if the '!' weren't there, it would indeed be a function declaration, but with improper syntax (removing the '!' would result in a syntax error). What makes a function either an expression or declaration is simply whether the parser expects an expression or declaration in the given context. The grouping operator '()' and the NOT operator '!' both are parameterized by expressions, and so the Javascript parser treats functions passed to them as expressions. Unless located where an expression is expected, functions will default to declarations.
- rmrfrmrf 12y agoYou're right, my mistake. Brain cramp :)
- kyllo 12y agoI liked one of the responses to the SO thread: http://stackoverflow.com/questions/3755606/what-does-the-exclamation-mark-do-before-the-function http://stackoverflow.com/questions/3755606/what-does-the-exc... !function () {}() This will also return the boolean opposite of the return value of the function, in this case true, because !undefined is true. If you want the actual return value to be the result of the call, then try doing it this way: (function () {})() Why would you ever not want the actual return value of a function to be the result of calling that function?