Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript plus sign in front of function expression

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?

like image 761
jOpacic Avatar asked Nov 12 '12 10:11

jOpacic


People also ask

What is plus sign in front of variable JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming. The plus(+) sign before the variables defines that the variable you are going to use is a number variable.

What does plus sign do in JavaScript?

The + operator returns the numeric representation of the object.

What is the meaning of += in JavaScript?

The addition assignment operator ( += ) adds the value of the right operand to a variable and assigns the result to the variable. The types of the two operands determine the behavior of the addition assignment operator. Addition or concatenation is possible.

What is $$ JavaScript?

$ and $$ are valid variable names in JavaScript, they have no special meaning. Usually they set their value to library instances, in your example if you check the closure call, at the end of the file you'll see that $ is jQuery in this case if it is defined and $$ is cytoscape.


1 Answers

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!"); }()); 
like image 86
T.J. Crowder Avatar answered Oct 12 '22 14:10

T.J. Crowder