+ 4
Math with JavaScript Strings
This question comes from a timed JavaScript Challenge: What is the output; console.log(1 - "1" + "1"); The output is 01. I was not expecting the subtraction in 1 - "1" . I would have expected 111 with 2nd and 3rd ones being a result on concatenation. Is this an example of automatic parsing? I'm not even sure if that is a thing. Thank you very much!
6 ответов
+ 3
DumbledoresAmy In short, arithmetic operator may change the data type of the underlying value:
'1' + 1 + 1 ▶ 111
1 + 1 + '1' ▶ 21
+'1' + 1 + 1 ▶ 3
The confusion arises when the symbol + can be used for addition and string concatenation as well.
Besides, seeing your problem was already resolved it would be great if you can mark the answer that you find useful to encourage the community to help each other out. 😉
+ 8
I think its becuase + is used for string concatenation and - is not, so because you used 1- the next operand become a number giving you 0 then using concat you add 0 to 1 giving you a string "01".
it seems to be that what ever operand is after the minus operator is converted to a number but if an + is used with a string it converts back to string.
+ 4
DumbledoresAmy your welcome and please do 👍
+ 3
D_Stark Fascinating! Thank you for your expertise!
+ 3
D_Stark The whole output is a string. I'll tag you in my experimental code 😎
+ 1
Zephyr Koo Thank you for answering the question and filling me in about Best Answer. I never noticed that capability before.