4

Can anyone tell me why and how the expression 1+ +"2"+3 in JavaScript results in 6 and that too is a number? I don't understand how introducing a single space in between the two + operators converts the string to a number.

Krisztián Balla
  • 19,223
  • 13
  • 68
  • 84
Ankur Tripathi
  • 53
  • 1
  • 1
  • 5
  • 4
    It doesn't result 5, it results 6. See [Unary +](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus) at MDN. – Teemu Sep 14 '18 at 06:29
  • 2
    How is that a `5`, i got `6`! Btw, that `+` will evaluate the string to `Number`. – choz Sep 14 '18 at 06:30

4 Answers4

6

Using +"2" casts the string value ("2") to a number, therefore the exrpession evaluates to 6 because it essentially evaluates to 1 + (+"2") + 3 which in turn evaluates to 1 + 2 + 3.

console.log(1 + +"2" + 3);
console.log(typeof "2");
console.log(typeof(+"2"));

If you do not space the two + symbols apart, they are parsed as the ++ (increment value) operator.

Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
1

It's simple first it convert the string +"2" to number(According to the operator precedence) and then add all these.

For Operator precedence mozilla developer link

Srikrushna
  • 4,366
  • 2
  • 39
  • 46
1
  • 1+ +"2"+3 results 6
  • 1+"2"+3 results "123"

The unary + operator converts its operand to the Number type.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Siddharth Jain
  • 336
  • 2
  • 9
0

+"2" is a way to cast the string "2" to the number 2. The remain is a simple addition.

The space between the two + operators is needed to avoid the confusion with the (pre/post)-increment operator ++.

Note that the cast is done before the addition because the unary operator + has a priority greater than the addition operator. See this table: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence#Table

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75