912

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?

Robert Siemer
  • 32,405
  • 11
  • 84
  • 94
jOpacic
  • 9,453
  • 12
  • 36
  • 58

4 Answers4

1360

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!"); }());
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 13
    More elaboration is here, http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – Kundan Singh Chouhan Nov 12 '12 at 10:14
  • 170
    Can't we say that the paren-wrapping is a superior notation? I'm VERY familiar with parens serving to encompass expressions. It's not clear at all what + is doing in this case if you don't already know this arcane quirk of js. – Chris Nov 13 '12 at 19:03
  • 1
    Note: Of the two parens options, **jsLint** prefers the second one. I think **jsHint** is less fussy. – Beetroot-Beetroot Aug 11 '13 at 23:21
  • 45
    One of the commonly used libraries that uses the "plus" notation is [Bootstrap](http://getbootstrap.com/) (which is how I ended up reading this thread). – Ville Oct 21 '14 at 21:57
  • Bootstrap is doing this, btw: https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js – AlexGrafe Oct 26 '14 at 11:01
  • *But when I say "correct" above, I mean syntactically, not in a broader sense.* As @Beetroot-Beetroot points out, in the narrowly broader sense of [JSLint, parens are, in fact, correcter](http://www.jameswiseman.com/blog/2011/02/17/jslint-messages-wrap-an-immediate-function-invocation-in-parentheses/). ;^) – ruffin Sep 08 '15 at 22:42
102

Subsidiary to @TJCrowder's answer, + is usually used to force numerical casting of a value 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"; })());
Community
  • 1
  • 1
Phil H
  • 19,928
  • 7
  • 68
  • 105
  • 5
    How did this ever get 37 upvotes? The `(+function() { ... })()` notation can never execute without errors (apart from the fact that this doesn't answer the question). – Catherine Nov 15 '12 at 21:21
  • 9
    @whitequark: Missed a pair of braces around the function+call. Suspect the upvotes were more because of the number casting explanation. – Phil H Nov 15 '12 at 22:46
  • 11
    OK I might have been nitpicking. – Catherine Nov 16 '12 at 13:13
  • 1
    You have some unnecessary brackets there, it is completely sufficient to do this: `3 + +function(){ return "4"; }();` – Christoph Dec 11 '12 at 08:54
  • 2
    @Christoph I'd be inclined to leave those brackets there. In fact, I would go so far as to add them if they were missing. It makes it much more clear what is going on, and also prevents issues when the code is minimized by removing the spaces, leading to `3++function...` which is not the same. – Benjam Nov 20 '13 at 17:41
  • 3
    Although on further reflection, the `+function...` is unnecessary in itself. The same result can be had with `blah + function( ){ ... }( );` which would negate the need for the wrapping brackets. – Benjam Nov 20 '13 at 17:47
65

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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 51
    Void or parentheses are *immensely* preferable. They are WTF-free. Using + is the sort of cleverness that isn't very smart. – Peter Wone Mar 16 '15 at 10:08
  • 2
    A good point. It seems like using one of the operators would move against what is presently industry standard. Perhaps "cool kid" developers would opt for it, otherwise I'm still not seeing a point of using something rather than void or () – dudewad Nov 09 '15 at 23:51
1

TL;DR (Quick Answer)

Plus Sign Casts (Converts) the proceeding operand to a Number if it isn't already.

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.

Stas Sorokin
  • 3,029
  • 26
  • 18
  • 1
    The unary `+` operator's *side-effect* is that it coerces its argument to number. This is in my opinion quite counter-intuitive, especially considering that binary `+` operator, for instance, also performs string concatenation. So `'hello' + 'world'` becomes `'helloworld'` but `+'hello'` becomes `NaN`, rather than `'hello'` which would be the result of concatenation with an empty string. – Peter Bašista Oct 12 '22 at 14:06