Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  161] [ 2]  / answers: 1 / hits: 93018  / 12 Years ago, mon, november 12, 2012, 12:00:00

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?


More From » function

 Answers
22

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!); }());

[#82044] Saturday, November 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aden

Total Points: 369
Total Questions: 100
Total Answers: 83

Location: Australia
Member since Tue, Oct 19, 2021
3 Years ago
;