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?
JavascriptWeb DevelopmentObject Oriented Programming. The plus(+) sign before the variables defines that the variable you are going to use is a number variable.
The + operator returns the numeric representation of the object.
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.
$ 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.
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!"); }());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With