Reputation:
Yesterday i have started courses on W3Schools. I am a little confused about one for loop in JavaScript.
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
It gives the following output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
What I am little confused is:
The text value it's updated with every iteration, so, after first iteration:
The number is 0
As text = The number is 0
Then are the next ones, and I can't understand why it prints out "the number is 1" and so on, instead of
The number is 0 The number is 1
The number is 0 The number is 1 The number is 2
The number is 0 The number is 1 The number is 2 The number is 3
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4
As with every next iteration the var text is updated and the for loop doesn't quit for loop to reset the value to var text = ""
Upvotes: 0
Views: 88
Reputation: 4309
That's because you accumulate the text inside a variable and then at the end print it.
If you watch the evolution of the text
variable using a debugger you would see what you describe at the end.
Upvotes: 1