My JavaScript code calculates the average of numbers as they are entered by pressing the add button. The added numbers are displayed on the screen, and if no number is entered, an "empty string" message is shown. However, I am facing an issue where the "empty string" text continues to be displayed even after entering numbers.
Initially, the code worked correctly when numbers were provided manually without user input. But when I allowed users to enter numbers themselves, the average calculation started malfunctioning.
Here is a snippet of the problematic code:
<body>
<h2>Average Function</h2>
<p>Press the button below to add numbers to the array:<br>
<button onclick="addNum()">Add</button>
</p>
<p id="numInArray"></p>
<p id="average"></p>
<!--JS Code-->
<script>
var grades = [];
function addNum() {
var grade = prompt("Add a number");
grades[grades.length] = grade;
document.getElementById("numInArray"). innerHTML =
"Numbers in array are: " + grades;
}
var sum = 0;
if (grades.length > 0) {
for (index = 0; index < grades.length; index++) {
sum += grades[index];
}
document.getElementById("average").innerHTML = sum/grades.length;
}
else {
document.getElementById("average").innerHTML = "Empty string";
}
</script>
</body>