<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x="";
for (var i=0;i<5;i++)
{
x=x + "The number is " + i +"<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
</body>
</html>
1- The document.getElementById("demo").innerHTML=x; is outisde the loop. So why does it show 5 values instead of one?
2- The result is:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
But why? After x="The number is 0 "<br>"" the next value of x should be "The number is 0 "<br>"The number is 1 "<br>". And it should keep adding each line to it. Why is it considering x="" everytime the loop is run. The var x="" is outside the loop?
Please help...very confused here by these two problems.