Mohamed Mostafa
Mohamed Mostafa

Reputation: 11

Why the output is 01122?

If we concatenate string and integers in Javascript the output must be the string part and then other numbers will be printed as string also, but in this it printed the zero then the number counted as integers not string and result the sum.

What is happening here?

var x = document.getElementById("1");
x.innerHTML += 1111 + 11;
<p id="1">0</p>

I expect the output of 01122 to be 0111111 or 1122

Upvotes: 0

Views: 41

Answers (1)

Sami Hult
Sami Hult

Reputation: 3082

You are concatenating to a string the sum of 1111 and 11 (=1122).

Javascript will first evaluate the sum, then convert it to a string for concatenation, since you are asking to add it to the end of a string (+=).

If you want to get 0111111:

x.innerHTML += '' + 1111 + 11;

If you want to get 1122:

x.innerHTML = +x.innerHTML + 1111 + 11;

Upvotes: 3

Related Questions