I am very confused between string and number addition as you can see in this code I can't add "i"
with "1" as a number like whenever I try to do "document.getElementById("demo").innerHTML = text += "
" + i + 1;" I get answer 11 BTW the value of "i" is 1. I have found a solution for this but the thing is that i is also a number and 1 of course is then why I have to follow some strange pattern. For more information read the code below:
function myFunction() {
var text = "";
var i;
Loop1:
for (i = 0; i < 10; i++) {
document.getElementById("demo").innerHTML = text += "<br>" + i + 1;
}
}
I can't write it like this because the computer will concat it like strings. So the solution I found looks like this:
function myFunction() {
var text = "";
var i;
for (i = 0; i < 10; i++) {
document.getElementById("demo").innerHTML = text += "<br>" + Number(i+1);
}
}
<body onLoad="myFunction()">
<span id="demo"><span>
</body>
This works just fine but I don't understand why since I am new in the coding world.
" + (i + 1);` Use parentehsis, currently everything is converted to a string. – Teemu Nov 05 '20 at 15:39