+ 2

Could you explain?

var z = "20"; var y = z*2+20; document.write(y); //output: 60 As we know in Javascript when adding a number and a string, JavaScript will treat the number as a string. could you explain what happened in the example above. var x = "20"; var y = 20; var z = x+y; document.write(typeof(z)); //output: string //z=2020 var x = "20"; var y = 20; var z = x*y; document.write(typeof(z)); //output: number //z=400

15th Aug 2019, 8:04 AM
Safaa Alnabhan
Safaa Alnabhan - avatar
7 Réponses
+ 7
i'm not really into javascript, but what is clear here is that "+" is for concatenation so when you add plus between string and a number it will concatenate them, but that doesn't go to *,/,- , so when multiplying, subtracting, dividing a string with a number it will change this string to a number.. that's what i think of. Hope this helps ^ ^.
15th Aug 2019, 8:22 AM
Anon Fox
Anon Fox - avatar
+ 4
i don't really know why but this is how it works. Best of luck☺️
15th Aug 2019, 8:58 AM
Anon Fox
Anon Fox - avatar
+ 4
In JavaScript, there is only one operator used for string which is plus(+).
17th Aug 2019, 2:15 AM
Pardeep Verma
Pardeep Verma - avatar
+ 2
TA .A thank you for your help .. my question is why does javascript treat "20" as string only with adding operator .. php is different and treats all the same but here the situation is different, why is it different with adding operator ☺
15th Aug 2019, 8:53 AM
Safaa Alnabhan
Safaa Alnabhan - avatar
+ 2
Safaa Alnabhan "Implicit Conversion: There are various operator and functions in JavaScript which automatically converts a value to the right type like alert() function in JavaScript accepts any value and convert it into a string. " quote from GeeksforGeeks https://www.geeksforgeeks.org/javascript-type-conversion/
15th Aug 2019, 11:44 AM
ODLNT
ODLNT - avatar
+ 2
The JavaScript compiler treats a number as a string if it is added after a string. Because the JS compiler treats String member as the first priority. Everything after a string will be treated as a string only. Consider var x = "Hello" var y = 20; var z = 20; console.log(x+y+z); // You will think output is : Hello40 // but the actual output is Hello2020.
15th Aug 2019, 3:01 PM
Rohan Rao
Rohan Rao - avatar
- 1
javascrib
15th Aug 2019, 7:07 PM
Driss Benjarmoun
Driss Benjarmoun - avatar