javascript tutorial - [Solved-3 Solutions] Javascript plus sign in front of function name - javascript - java script - javascript array



Problem:

I've been looking on info about self-invoking functions, and somewhere we stumbled on this notation:

+function(){}
click below button to copy the code. By JavaScript tutorial team

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

Solution 1:

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!"); }();
click below button to copy the code. By JavaScript tutorial team

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, we can use parentheses (this is more common, but neither more nor less correct syntactically):

(function() { console.log("Foo!"); })();
// or
(function() { console.log("Foo!"); }());
click below button to copy the code. By JavaScript tutorial team

Solution 2:

In this instance it is called the 'unary plus operator' (for ease of googling).

var num = +variant;
click below button to copy the code. By JavaScript tutorial team

So in front of a function it can be a way to force the function's result to be interpreted as a number. We doubt it happens yet, but theoretically the JIT could use that to compile the function as a numerical-only function etc. However, to prevent the unary plus being a concatenation when used in a larger expression, we would need parentheses:

blah + (+(function(){ var scope; return "4"; })());
click below button to copy the code. By JavaScript tutorial team

Solution 3:

So the short answer is that it prevents a syntax error, by using the function results in one way or another. We can also instruct the engine that you're not even interested in the return value by using the void operator:

void function() { console.log("Foo!"); }();
click below button to copy the code. By JavaScript tutorial team

Of course, putting braces around the whole thing also serves that purpose.


Related Searches to javascript tutorial - Javascript plus sign in front of function name