This question was asked before: Trouble understanding what happens during javascript for loop but the asker didn't get the right answer and so did I. I learn C++ and Python earlier so I get familiar with loop but when I practing this code:
let text = "";
let i;
for(i=0; i<5; i++)
{text += "The number is " + i + " ";}
document.write(text);
the output is totally different to what I expected. I visited W3schools but I can't find the answer https://www.w3schools.com/js/js_loop_for.asp
https://www.w3schools.com/js/tryit.asp?filename=tryjs_loop_for_om3
I expected the output is "" because text can't be changed but the code prints out: "The number is 0 The number is 1 The number is 2 The number is 3 The number is 4". My question is why the print executes in the loop though the print is outside the loop? Thank you very much!
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.
why the output not empty string because the text variable not empty anymore after for loop. you have assign string when loop so the text variable not empty anymore