-1

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 = ""

3
  • The code you posted does not have any "output" at all. It just accumulates strings. What happens with text after that loop? Commented Dec 30, 2015 at 14:21
  • document.getElementById("demo").innerHTML = text; It is this task from linkW3schools //EDIT - doesn't matter anyways, I understood now :) :) Commented Dec 30, 2015 at 14:26
  • It's because of the + in text +=, it means "add to the previous value", remove it and text's value will be overwritten by new content each iteration. Commented Dec 30, 2015 at 14:28

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.