JavaScript plus sign in front of function expression

JavascriptFunctionOperatorsIifeSelf Invoking-Function

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Subsidiary to @TJCrowder's answer, + is usually used to force numerical casting of a value https://stackoverflow.com/questions/5450076/whats-the-significant-use-of-unary-plus-and-minus-operators">as this SO answer explains. In this instance it is called the 'unary plus operator' (for ease of googling).

var num = +variant;

So in front of a function it can be a way to force the function's result to be interpreted as a number. I 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, you would need parentheses:

blah + (+(function(){ var scope; return "4"; })());

Solution 3 - Javascript

So the short answer is that it prevents a syntax error, by using the function results in one way or another.

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

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

Solution 4 - Javascript

Solution & Origins

The + sign before the function, actually called Unary plus and is part of a group called a Unary Operators and (the Unary Plus) is used to convert string and other representations to numbers (integers or floats).

> A unary operation is an operation with only one operand, i.e. a single > input. This is in contrast to binary operations, which use two > operands

Basic Uses:

const x = "1";
const y = "-1";
const n = "7.77";

console.log(+x);
// expected output: 1

console.log(+n);
// expected output: 7.77

console.log(+y);
// expected output: -1

console.log(+'');
// expected output: 0

console.log(+true);
// expected output: 1

console.log(+false);
// expected output: 0

console.log(+'hello');
// expected output: NaN

When the + sign is positioned before a variable, function or any returned string representations the output will be converted to integer or float; the unary operator (+) converts as well the non-string values true, false, and null.

Advanced Uses

The right way to use the function you mentioned above will be:

+function(){return "3.141"}()
// expected output: 3.141

I love to use + to turn a new Date() object to a timestamp, like this:

+new Date()
// expected output: 1641387991035

Other Unary Operators

> - The unary negation operator converts its operand to Number type > and then negates it. > > ~ Bitwise NOT operator. > > ! Logical NOT operator. > > delete The delete operator deletes a property from an object. > > void The void operator discards an expression's return value. > > typeof The typeof operator determines the type of a given object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjOpacicView Question on Stackoverflow
Solution 1 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 2 - JavascriptPhil HView Answer on Stackoverflow
Solution 3 - JavascriptJa͢ckView Answer on Stackoverflow
Solution 4 - JavascriptStas SorokinView Answer on Stackoverflow