<!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>
I understand what it returns but I don’t understand the x before each statement.
x = x + "The number is " + i + "<br>";
x is a variable which is going to grow over the loop.
The line:
just appends the line
“The number is ” + i + end of line
to the current value of x.
Think of this line as:
At the end of the loop, x is worth all that:
“The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
“
If instead of x = “”, you had x = “Hello, “, then the final result would be:
“Hello, The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
“