Math with JavaScript Strings | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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!

25th Nov 2018, 10:51 PM
DumbledoresAmy
DumbledoresAmy - avatar
6 Answers
+ 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. 😉
26th Nov 2018, 4:46 AM
Zephyr Koo
Zephyr Koo - avatar
+ 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.
25th Nov 2018, 11:24 PM
D_Stark
D_Stark - avatar
+ 4
DumbledoresAmy your welcome and please do 👍
26th Nov 2018, 12:11 AM
D_Stark
D_Stark - avatar
+ 3
D_Stark Fascinating! Thank you for your expertise!
26th Nov 2018, 12:00 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 3
D_Stark The whole output is a string. I'll tag you in my experimental code 😎
26th Nov 2018, 12:07 AM
DumbledoresAmy
DumbledoresAmy - avatar
+ 1
Zephyr Koo Thank you for answering the question and filling me in about Best Answer. I never noticed that capability before.
26th Nov 2018, 5:50 AM
DumbledoresAmy
DumbledoresAmy - avatar