JavaScript type conversion examples? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 17

JavaScript type conversion examples?

Type conversion in JS is confusing to me. It's my hope that here through examples I can learn how it works. Oh man my head is spinning.

20th Mar 2017, 9:24 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
7 Answers
+ 33
@Joe I don't know the term but JS is weakly typed, so there are so many weird cases. For your examples: "20" is string and 20 is integer. "20"+20 makes it string concatenation as string is before int. So ans is 2020. But for 20/" 20" as int is first "20" is converted to int 20. So ans is 1.
20th Mar 2017, 12:16 PM
Ram chandra Giri
Ram chandra Giri - avatar
+ 16
Feel the weirdness. JS type conversion. Table stolen from w3 schools. Original Value Converted to Number Converted to String Converted to Boolean false 0 "false" false true 1 "true" true 0 0 "0" false 1 1 "1" true "0" 0 "0" true "000" 0 "000" true "1" 1 "1" true NaN NaN "NaN" false Infinity Infinity "Infinity" true -Infinity -Infinity "-Infinity" true "" 0 "" false "20" 20 "20" true "twenty" NaN "twenty" true [ ] 0 "" true [20] 20 "20" true [10,20] NaN "10,20" true ["twenty"] NaN "twenty" true ["ten","twenty"] NaN "ten,twenty" true function() {}NaN "function(){}" true
20th Mar 2017, 9:48 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 15
20 + false = 20 + 0 = 20 The first thing JS sees is type number so it converts the bool false to zero. hoo boy.
20th Mar 2017, 10:10 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 13
Mr. Ram very helpful answer thank you!
20th Mar 2017, 12:30 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 13
30/"30" = 1 why? 30 is first thing it encounters. 30 is a number. so now it must convert the numeric string "30" to a number. so 30/"30" = 30/30 = 1. Thank you Mr. Ram chandra Giri.
20th Mar 2017, 9:23 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 12
"20" + 20 = 2020 why? "20" (a string) is first, so it must convert the number 20 into a string, "20" so "20" + 20 = "20" + "20" = 2020. Thank you Mr. Ram chandra Giri!
20th Mar 2017, 9:26 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 3
i think it just javascript behavior,, i don't bother
20th Mar 2017, 12:09 PM
Yuliana
Yuliana - avatar