+ 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.
7 RĂ©ponses
+ 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.
+ 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
+ 15
20 + false = 20 + 0 = 20
The first thing JS sees is type number so it converts the bool false to zero. hoo boy.
+ 13
Mr. Ram very helpful answer thank you!
+ 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.
+ 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!
+ 3
i think it just javascript behavior,, i don't bother