Comment

Comment by rmrfrmrf

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.

parent rmrfrmrf 12 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton