JS: Arrays
Theory: Aggregation
One reason loops are used with arrays is aggregation. Aggregation is any calculation that is, as a rule, based on the entire data set, such as finding the maximum, average, sum, etc. of all the data. The aggregation process does not require knowledge of new syntax, but it affects the problem-solving algorithm. Therefore, it makes sense to consider it separately. Let's start by looking for the maximum.
Why is this an example of aggregation? Here we see a calculation that involves comparing all the elements to find the one that will be the result of this operation.
Note that the initial value of max is the first element, not, say, the number 0. After all, it may turn out that all numbers in the array are less than 0, and then we will get the wrong answer.
Now consider searching for the sum:
The algorithm for finding the sum is much simpler, but has a couple of important nuances.
What is the sum of the elements of the empty array? As far as mathematics is concerned, such a sum equals 0. Seems like common sense. If we have no apples, then we have 0 apples (the number of apples is zero). Functions in programming work according to this logic.
The second point has to do with the initial element of the sum. The variable sum has an initial value of 0. Why set a value at all? Any repetitive operation starts with a value. You can't just declare a variable and start working with it inside a loop. This will lead to an incorrect result:
The result of this call will be NaN, i.e., a not-a-number, inside sum. It comes from trying to add 2 and undefined. So a value is needed after all. Why is 0 selected in the code above? It is very straightforward to check that all other options will lead to the wrong result. If the initial value is 1, then the result is 1 higher than it should be.
In mathematics, there is a concept of a neutral or identity element of an operation (each operation has its own element). This concept has a very simple meaning. An operation with this element does not change the value on which the operation is performed. In addition, any number plus zero gives the number itself. The same applies for subtraction. Even concatenation has a neutral element, which is an empty string: '' + 'one' will be 'one'.
Aggregation does not always mean that a collection of elements is reduced to a simple value. The result of aggregation can be any complex structure, such as an array. Such examples are often found in real life. The simplest example is a list of unique words in a text.

