+ 2
var x="2"+4+5; document.write(x); output is 245. But how??
2 should be treated as a string and 4+5 should be added and the output should be 29 but it's 245 how 😥?
1 Respuesta
+ 4
Expressions in JavaScript are evaluated from left to right
(this is known as associativity)
Thus when a string is encountered first by the compiler, it converts the whole expression into a string.
Hence your output is 245.
To perform addition first, you must enclose 4+5 in brackets, like this
var x = "2" + (4+5);
Now JavaScript first evaluated the bracket, thus output will be 29, on printing the variable x