JavaScript plus sign in front of function expression

jOpacic picture jOpacic · Nov 12, 2012 · Viewed 84.9k times · Source

I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:

+function(){console.log("Something.")}()

Can someone explain to me what the + sign in front of the function means/does?

Answer

T.J. Crowder picture T.J. Crowder · Nov 12, 2012

It forces the parser to treat the part following the + as an expression. This is usually used for functions that are invoked immediately, e.g.:

+function() { console.log("Foo!"); }();

Without the + there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word function looks like the beginning of a function declaration rather than a function expression and so the () following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). With the +, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.

+ is just one of the options. It can also be -, !, ~, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):

(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());