1

From what I have poorly remembered before, javascript tries to convert the operands to a similar type before doing the operation. However, when I tried to do the following in the console:

+'11111'
*'11111'

They produce different results - addition parses, multiplication fails. This means what I remembered was wrong. What is the exact reason that + works? I have also seen people use it in IIFEs

+(function() {

})()

//the same as:

;(function() {

})()

  • 2
    Besides being in the language specification, probably because the prefix `+` operator makes mathematical sense? I.e. `+123` is a valid number. `*123` isn't. – Some programmer dude Sep 16 '20 at 02:39

2 Answers2

5

+'11111' results in the number 11111 because unary + converts the expression on its right side to a number. But there's no such thing as "unary *", so *'11111' throws an error. (What would *'11111' even mean?)

As for the IIFEs:

;(function() {

})()

the ; ensures that the IIFE starts after the end of the previous statement. Were it not for the ;, and the previous statement did not end with a ;, the lack of Automatic Semicolon Insertion on the previous line could cause bugs:

const arr = []

(function() {

})()

But using + without a semicolon on the previous line is not a good idea, because then the return value of the IIFE can be added or concatenated to the previous line:

const arr = []

+(function() {

})()

console.log(arr);

If you always put semicolons at the end of statements when appropriate, then there's no need to put anything before the ( of an IIFE:

const arr = [];
(function() {
  console.log('iife');
})();
console.log(arr);

(If you aren't an expert, I'd recommend using semicolons, rather than relying on the slightly strange rules of ASI - they'll sometimes result in hard-to-understand bugs)

CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
  • 2
    I think OP misread the IIFE case, sometimes (code-golf) `+function(){}()` is used in place of `(function(){})()` – Kaiido Sep 16 '20 at 02:46
1

There is a good explanation and examples here and here for JavaScript Unary Operators.

TDLR: The unary operation tries to convert anything to a number, and if it can't success it will return NaN

+3                                   // returns 3
+'-3'                                // returns -3
+'3.14'                              // returns 3.14
+'3'                                 // returns 3
+'0xFF'                              // returns 255
+true                                // returns 1
+'123e-5'                            // returns 0.00123
+false                               // returns 0
+null                                // returns 0
+'Infinity'                          // returns Infinity
+'infinity'                          // returns NaN
+function(val){  return val }        // returns NaN
Liron
  • 171
  • 1
  • 8