function calculateAverage() {
var total = 0;
var arr = [];
while (true) {
var input = Number(prompt("Please enter a value"));
if (input !== 0) {
arr.push(input);
total = arr.reduce(
(accumulator, currentValue) => accumulator + currentValue
);
} else {
alert("Values in array: " + arr);
alert("Total sum: " + total);
alert("Average: " + (total / arr.length));
break;
}
}
}
I have developed a JavaScript program to calculate the sum, average of numbers in an array, and display the array. The code is functioning correctly, but I have a question regarding it.
When I initialize the empty array var arr=[];
outside the while loop, the program works as expected. However, when I declare it within the if
block, the program only prints the last number added to the array during execution.
Being new to JavaScript, I am wondering if this issue relates to global versus local variables?
Any insights would be greatly appreciated.
Thank you!