0

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?

  • `html = ""` overwrites the content of `html` in every round of the loop. – Andreas Feb 11 '22 at 12:52
  • Just to be precise... `var html = ""` are two things at once. `var html` declares a variable. `html = ""` then assigns the empty string to that variable. – Andreas Feb 11 '22 at 12:54

1 Answers1

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.

idontcare
  • 26
  • 5