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

224
Visualizações
Why does declaring the variable outside the for loop print all the elements of an array but declaring first inside the for loop prints only the last?

Forgive me if something is wrong with my question, I am a beginner.

The first code, which has the variable "html" first declared outside the for loop, prints all the elements of the array.

<p id="demo"></p>
<script>
 var fruits = ["apple", "banana", "mango", "orange", "strawberry"];

 var html = "";
      
for(var i = 0; i < fruits.length; i++) {
   html += "<p>" + fruits[i] + "</p>";
     }
         document.getElementById("demo").innerHTML = html;
</script>

But when I move the variable declaration inside the for loop, only the last element of the array is printed.

    <p id="demo"></p>
<script>
 var fruits = ["apple", "banana", "mango", "orange", "strawberry"];
      
for(var i = 0; i < fruits.length; i++) {
    var html = "";
    html += "<p>" + fruits[i] + "</p>";
     }
         document.getElementById("demo").innerHTML = html;
</script>

Why is this?

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

0

That's because, when you declare the variable inside the loop, it will be declared each time the loop is repeated. So the last run of the loop will declare an empty variable 'html' and will then push the element into this array. So there is only one element inside your array.

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