The Error of Finding the Array Average
Let's consider an error related to finding the arithmetic mean of array elements. For example, let's say we have the following array:
let arr = [1, 2, 3, 4, 5];
To find the average of the elements, you need to find their sum and divide it by the quantity. A certain programmer has already solved this problem in the following way:
let avg = 0;
for (let elem of arr) {
avg += elem / arr.length;
}
console.log(avg);
Let's examine the problems with this solution. Technically, the code works correctly and gives the right answer. The fact is that mathematically it is correct to either divide the entire sum by the quantity, or divide each of the terms by the quantity.
However, another problem arises. The issue is that we will perform division as many times as there are elements in our array. It turns out that we are doing a large number of unnecessary operations, because the division could have been done at the end - only once, by dividing the entire found sum.
Let's optimize our code:
let sum = 0;
for (let elem of arr) {
sum += elem;
}
let avg = sum / arr.length;
console.log(avg);