Javascript prints value in loop though the print is outside the loop

The print executes as you expect: Only once at the end. In the loop, each time an extra part is appended to text. That is:

[iteration 0] ""
[iteration 1] "The number is 0 "
[iteration 2] "The number is 0 The number is 1"
[iteration 3] "The number is 0 The number is 1 The number is 2"
etc.

Then in the end, you print the final String which is the concatenation of all the partial Strings you 'glued' together.

Saying x += y is the same as saying x = x + y. Standard variables (var and let) are still mutable, so if you initialize it as an empty String, you can still append/replace it later.

Try making text a const instead, and there should be a runtime TypeError because you try to reassign a constant.