Search code examples
javascriptoperatorsconcatenationstring-concatenationarithmetic-expressions

Why does '+' operator behave abnormally in JavaScript?


I'm learning JavaScript.

I tried putting double quotes around different digits in an JavaScript expression and I got surprised with the third result from below code statements.

Consider below code statements and their output present in a comment ahead of each code line.

var x = "5" + 2 + 3;
document.getElementById("demo").innerHTML = x; //Output is : **523**

var x = 5 + "2" + 3;
document.getElementById("demo").innerHTML = x; //Output is : **523**

var x = 5 + 2 + "3";
document.getElementById("demo").innerHTML = x; //Output is : **73**

Can someone please explain why and how the '+' operator behaves abnormally in JavaScript?

Why the output of last statement is not 523 since one of the digits is a string?

Please explain me in a simple and lucid language.

Thanks.


Solution

  • Javascript executes the expressions left-to-right. So in the last example it will do this:

    5 + 2 => 7
    7 + "3" => "73"
    

    Hope that helps