2

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>
Ivar
  • 6,138
  • 12
  • 49
  • 61
jigyasa
  • 21
  • 1
  • 3

1 Answers1

8

+ 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
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320