- 1

Concatenating sting with number

The code below in javascript var x="20"; alert(x*1+20); Can someone explaine how this output= 40 ?

2nd Jul 2017, 3:42 PM
Shokly
4 Answers
+ 3
Because that time, only addition is perform with variable x, and it is treated as string that time. So that x and 20 can concat. 😅 JavaScript is very moody language.
2nd Jul 2017, 4:27 PM
Sachin Artani
Sachin Artani - avatar
+ 2
Simply, JavaScript is a multi talented language 😁 It automatically converts a datatype when needed. In your code, you performed some calculations, so x variable is treated as int, so calculated as- 20*1+20 which is 40
2nd Jul 2017, 4:04 PM
Sachin Artani
Sachin Artani - avatar
+ 1
20 * 1 = 20 20 + 20 = 40
2nd Jul 2017, 3:45 PM
Keto Z
Keto Z - avatar
0
but why when alert(x+20); the result is 2020?
2nd Jul 2017, 4:25 PM
Shokly