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 = ""
textafter that loop?text +=, it means "add to the previous value", remove it andtext's value will be overwritten by new content each iteration.