Reputation: 2440
Why in Javascript/HTML does addition of integers followed by the addition of a string followed by the addition of more integers result in the integers being added right away correctly but after the string they are treated essentially as a string?
Ex.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var y = 5 + 5 + 2 + "3" + 1 + 2;
document.getElementById("demo").innerHTML = "<br>" + y + "<br>"
</script>
</body>
</html>
Running this returns 12312, which is the addition of 5+5+2 and the string "3" but then concatenates 1 and 2 rather than adding...why is this?
Upvotes: 2
Views: 74
Reputation: 375
Once you add a string to an integer, the whole thing will remain a string so you just concatenate some additional numbers after that. You could use some brackets around the numbers to add them up before concatenating them.
Upvotes: 2
Reputation: 670
Calculations are performed left to right. The result after 5+5+2 is an integer; the result after 5 + 5 + 2 + "3" is a string. Adding a string to an integer always results in a string.
Upvotes: 5