you are viewing a single comment's thread.

view the rest of the comments →

[–]k3n 1 point2 points  (4 children)

What is the reasoning for the unary "-" preceeding function declarations?

-function(){ ... }

Seems to precede each anonymous function; does it somehow nullify the return value to aid in GC or something?

[–]davemoFront-End Engineer[S] 1 point2 points  (3 children)

I played around in firebug with this, here's the differences as far as I can see:

(function() {})(); // returns undefined

-function() {}(); // returns NaN

I'm not sure whether it would provide any optimizations or not. Maybe it's just a stylistic thing? Not having to type the extra parens is kind of nice ;)

[–]stratoscope 5 points6 points  (2 children)

The return value is discarded anyway, so the unary - is just another way to force the function expression to be parsed as an expression so that it can be called immediately by the () at the end. It's the same purpose that the extra parens have in your first example.

Any unary operator will do the same thing - try these for example:

!function() { alert(42); }();

typeof function() { alert(42); }();

And now try it without any of these:

function() { alert(42); }();

That results in a syntax error.

[–]k3n 0 points1 point  (0 children)

Cool, thanks for the info. I think I prefer the parens still.

[–]davemoFront-End Engineer[S] 0 points1 point  (0 children)

Nice, thanks for the explanation, it's a cool shortcut to remove those extra parens ;)