Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 1+ +"2"+3 evaluate to 6 in JavaScript? [duplicate]

Tags:

javascript

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.

like image 625
Ankur Tripathi Avatar asked Jan 27 '23 10:01

Ankur Tripathi


1 Answers

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.

like image 166
Angelos Chalaris Avatar answered Feb 01 '23 00:02

Angelos Chalaris