# Optimization of loop operations in JavaScript

Even an easy operation, repeated many times in a loop, can take a lot of resources.

Let's look at an example. Let's have some array:

`let arr = [1, 2, 3, 4, 5, 6];`

Let's find the average of this array elements. To do this, you need to find the sum of the elements and divide it by the amount. Suppose a 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 look at the problems of such a solution. Technically, the code works correctly and gives the correct answer. The fact is that it is mathematically correct both to divide the entire sum by the quantity, and to divide each of the terms by the quantity.

However, another problem arises. The point is that we will perform the division as many times as there are elements in our array. And it turns out that we are doing a large number of unnecessary operations, because the division could be performed at the end - once, dividing the entire sum found.

Let's optimize our code:

```let sum = 0; for (let elem of arr) { sum += elem; } let avg = sum / arr.length; console.log(avg);```

Optimize the following code:

```for (let i = 1900; i <= 2100; i++) { let curr = new Date; let date = new Date(i, curr.getMonth(), curr.getDate()); if (curr.getDay() === date.getDay()) { console.log(date); } }```

Optimize the following code:

```let obj = {a: 10, b: 20, c: 30, d: 40, e: 50}; let sum = 0; for (let key in obj) { if (String(obj[key])[0] === '1' || String(obj[key])[0] === '2') { sum += obj[key]; } } console.log(sum);```