Arno Lorentz Arno Lorentz - 11 days ago 8
Javascript Question

How does adding String with Integer work in JavaScript?

The following code gives weird results:



function showOutput() {
document.getElementById("demo").innerHTML = "" + 1 + 10 + 2 - 5 + "8";
}

<input type="button" value="Click me check output" onclick="showOutput()">
<p id="demo"></p>





I've tried inputting various different values to work it out but I cannot understand what's going on under the hood.

Answer
"" + 1 + 10 + 2 === "1102"
"1102" - 5      === 1097
1097 + "8"      === "10978"

In JavaScript, the + operator is used for both numeric addition and string concatenation. When you "add" a number to a string, you concatenate onto the string.

When you use the - operator, however, the string is converted back into a number so that numeric subtraction may occur.

When you then "add" a string "8", string concatenation occurs again.