Ravi kumar Ravi kumar - 2 months ago 8
HTML Question

JavaScript Variables Query understanding

I am new to JavaScript, can someone explain why these 3 results are different?




Example 1.

var x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;


Output: 10




Example 2.

var x = 5 + 2 + "3";
document.getElementById("demo").innerHTML = x;


Output: 73




Example 3.

var x = 5 + "2" + 3;
document.getElementById("demo").innerHTML = x;


Output: 523

Answer

+ is overloaded to perform string concatenation and addition, and it is left-to-right associative.

Because the operator is overloaded, there needs to be a rule how to resolve the situation where both operands are of different data types. This rule is simple:

If one operand is a string, convert the other operand to a string.

That means the code is evaluated as

// 1.
((5 + 2) + 3) 
 = 7 + 3 
 = 10

// 2.
((5 + 2) + "3")
  = 7 + "3"           // number + string -> convert number to string
  = "7" + "3" 
  = "73"

// 3.
(("5" + 2) + 3)       // number + string -> convert number to string
  = (("5" + "2") + 3)  
  = "52" + 3          // number + string -> convert number to string
  = "52" + "3" 
  = "523"