Interactive online courses HTML Academy
2026-03-09 12:23 Diff

In the first step of refactoring, we got rid of individual variables and intentionally turned off the calculation of the average value by writing zero into the variable averageUsers. It’s time to fix this mechanism, but with the use of an array.

Remember that the average value is the sum of all the elements divided by their number. We have already calculated the sum in the loop, and the number of elements can be obtained using [].length.

Refactoring is complete, and here is the cherry on the cake! Now the program has become much more flexible and allows you to easily analyze any amount of data (for a week, a month, or even a year). To do this, you just need to change the values ​​inside the array usersByDay.

Finally, complete Muffin’s task. Analyze traffic for the last month. To do this, copy this data into the array:

817, 1370, 752, 1247, 681, 1120, 915, 1281, 875, 1341, 757, 610, 812, 1170, 769, 1261, 845, 1289, 515, 1247, 845, 1311, 741, 1239, 812, 638, 877, 1242, 1159, 1372

Now the program is universal and works with arrays of any length. But there is one nuance. If you run the program on an empty array, then the average traffic value will be NaN (stands for not a number). It couldn’t be any other way, because in the formula for calculating the average value, zero will be the divisor and the divisible at the same time, and 0 / 0 gives us an undefined result, that is, NaN. It’s quite logical if you think about it: we cannot know the average value of non-existent values, therefore we can assume that our algorithm works as it should.