Why is "5" + 2+3 and 2+3+ "5" different in JavaScript?
This if giving me wrong result.
<p>The result of adding "5" + 2 + 3</p>
<p id="demo"></p>
<script>
x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>
<p> result of adding 2+3+"5"</p>
<p id="qwe"></p>
<script>
y = 2 + 3 + "5";
document.getElementById("qwe").innerHTML = y;
</script>
Why is "5" + 2+3 and 2+3+ "5" different in JavaScript?
This if giving me wrong result.
<p>The result of adding "5" + 2 + 3</p>
<p id="demo"></p>
<script>
x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>
<p> result of adding 2+3+"5"</p>
<p id="qwe"></p>
<script>
y = 2 + 3 + "5";
document.getElementById("qwe").innerHTML = y;
</script>
Share
Improve this question
edited Apr 22, 2020 at 12:34
Ivar
6,86712 gold badges56 silver badges67 bronze badges
asked Apr 22, 2020 at 12:26
jigyasajigyasa
211 silver badge3 bronze badges
2
- 2 What's the right result? What were you expecting? – Rup Commented Apr 22, 2020 at 12:29
- Does this answer your question? How does adding String with Integer work in JavaScript? – kevinSpaceyIsKeyserSöze Commented Apr 22, 2020 at 12:36
1 Answer
Reset to default 9+
evaluates left-to-right, so
"5" + 2+3
is equivalent to
("5" + 2) + 3
and the other one:
2+3+ "5"
is equivalent to:
(2 + 3) + "5"
When two numbers are +
d together, they are added, so the result is a number. But if either side of the +
is a string, the two expressions are concatenated instead of added. So
("5" + 2) + 3
// results in
'52' + 3
'523'
(2 + 3) + "5"
// results in
5 + '5'
55