'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source