+ 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
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 ^ ^.
+ 4
i don't really know why but this is how it works. Best of luck☺️
+ 4
In JavaScript, there is only one operator used for string which is plus(+).
+ 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 ☺
+ 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/
+ 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.
- 1
javascrib