Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  88] [ 4]  / answers: 1 / hits: 51799  / 8 Years ago, mon, november 28, 2016, 12:00:00

The following code gives weird results:





console.log( + 1 + 10 + 2 - 5 + 8);





I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.


More From » string

 Answers
4
 + 1          === 1
1 + 10 === 110
110 + 2 === 1102
1102 - 5 === 1097
1097 + 8 === 10978


In JavaScript, the + operator is used for both numeric addition and string concatenation. When you add a number to a string the interpreter converts your number to a string and concatenates both together.



When you use the - operator, however, the string is converted back into a number so that numeric subtraction may occur.



When you then add a string 8, string concatenation occurs again. The number 1097 is converted into the string 1097, and then joined with 8.


[#59895] Friday, November 25, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leslijessalyng

Total Points: 650
Total Questions: 85
Total Answers: 109

Location: Croatia
Member since Mon, Sep 6, 2021
3 Years ago
leslijessalyng questions
Fri, Feb 21, 20, 00:00, 4 Years ago
Tue, Jul 30, 19, 00:00, 5 Years ago
Fri, Jul 5, 19, 00:00, 5 Years ago
Wed, Mar 13, 19, 00:00, 5 Years ago
;