'how to prevent innerHTML repeating the previous value

I'm a JS learner and want to create an app that will calculate the average from input values. So far I've managed to push the entered input values into an array. However, when I want to display them, the previous value is repeated. So I'm near the end. But now I'm stuck. Can you lend me hand with that?

        Enter
      </button>
      <p id="numbersEntered"></p>
      <button id="avg" type="button">Average</button>
      <p id="average"></p>
  
   let numbersEntered = document.querySelector("#numbersEntered");
   let inputEl = document.querySelector("#input");

   // buttons
   let enter = document.querySelector("#enter");

   let numArr = [];

   enter.addEventListener("click", displayNums);

   function displayNums() {
   let newNumber = inputEl.value;
   numArr.push(newNumber);
   console.log(numArr);

   for (let i = 0; i < numArr.length; i++) {
    numbersEntered.innerHTML += numArr[i] + ",";
  }
  }



Solution 1:[1]

Instead of appending numArr to innerHTML, simply overwrite it instead. Also, since you're only writing plain text, it is recommended to use textContent instead of innerHTML:

function displayNums() {
    let newNumber = inputEl.value;
    numArr.push(newNumber);
    console.log(numArr);

    numbersEntered.textContent = numArr.join(', ');
}

There is no need to use a for loop when you can use Array.prototype.join to print the array out.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1