Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

233
Visualizações
Javascript prints value in loop though the print is outside the loop

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!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda