How do I update the innerHTML of a div with the contents of a JS array after pushing new items into it?

I have an array with three items in it, and four buttons – each adds a new item to the array.

Pushing items into the array with the buttons is working fine, but, as for the div where the items are displayed, it does not update correctly. The first item I push always shows up on the div correctly, but from there on, everytime I click on one of the remaining buttons, the same items shows up.

What am I doing wrong here?

JSFiddle

var inventory = ["Apple", "Pear", "Orange"];

for (i = 0; i < inventory.length; i++)
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";

function addItem(newItem, itemBtn) {
  inventory.push(newItem);
  document.getElementById(itemBtn).style.display = "none";
  console.log(inventory);
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";
}
<p>Fruits:</p>
<div id="arrayDiv"></div>
<hr>
<input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
<input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
<input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
<input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">

Answer

inventory[i] the variable i is fixed to one value after your for loop is executed.

After loop prints [“Apple”, “Pear”, “Orange”] the value of i is now stuck at 3.

(Apple => 0, Pear => 1, Orange => 2), hence the next value on i is 3 due to i++ of the for loop

Thus, you can be getting the same Fruit name displayed in HTML.

To avoid that problem, just use newItem instead of inventory[i].

var inventory = ["Apple", "Pear", "Orange"];

for (i = 0; i < inventory.length; i++)
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";

function addItem(newItem, itemBtn) {
   
  inventory.push(newItem);
  document.getElementById(itemBtn).style.display = "none";
  
  document.getElementById("arrayDiv").innerHTML += newItem + "<br>";
}
<p>Fruits:</p>
<div id="arrayDiv"></div>
<hr>
<input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
<input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
<input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
<input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">