0

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!

  • 1
    You don't print in the loop. You keep adding more content to the variable called `text` and you print only once, after the loop has finished – malarres Jan 18 '22 at 07:51
  • Thanks for answering but why text is not empty string since it was initialized as text = ""? –  Jan 18 '22 at 07:55
  • 1
    the loop will completely execute before your document.write, so all your concatinations will apply – john Smith Jan 18 '22 at 08:02
  • I totally forgot that text was reassigned. I was confused with the context string is immutable, can't replace characters in it. Thank you! –  Jan 18 '22 at 08:22

2 Answers2

3

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.

fravolt
  • 2,565
  • 1
  • 4
  • 19
  • How about "Javascript strings are immutable"? I print the text variable, and it should be empty string, why it prints out the string that was added through the loop? –  Jan 18 '22 at 08:00
  • I totally forgot that text was reassigned. I was confused with the context string is immutable, can't replace characters in it. Thank you! –  Jan 18 '22 at 08:24
0

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

  • Thank you for pointing it out! I totally forgot that text was reassigned. I was confused with the context string is immutable, can't replace characters in it. Thank you! –  Jan 18 '22 at 08:21