## DEV Community Dooder

Posted on • Updated on

# Find the Average of a Given Array of Numbers

## Find the average of all numbers in a given array

Let's say we wanted to write a function that calculates the average of all grades (including yours). We can do this in many different ways in JavaScript, but in this demo I will be showing you how to find the average using Higher-Order Functions and the "for" loop.

### forEach loop

The forEach() method executes a provided function once for each array element.

``````const yourGrade = 88;
87, 68, 94, 100, 83,
78, 85, 91, 76, 87
];

function average(array) {
// initialize value of `sum`
let sum = 0;
// capture the length of the array
let arrayLength = array.length;
// loop through the array via forEach
});
// formula to calculate average: sum / arrayLength
return Math.round(sum / arrayLength);
}
console.log(avg);
``````

### for loop

The `for()` loop iterates a specified amount of times, and does "something" that many times.

``````const yourGrade = 88;
87, 68, 94, 100, 83,
78, 85, 91, 76, 87
];

function average(array) {
// initialize value of `sum`
let sum = 0;
// capture the length of the array
let arrayLength = array.length;
// iterate over the array
for (let i = 0; i < array.length; i++) {
// add each element to the `sum`
sum += array[i];
}
// formula to calculate average: sum / arrayLength
/* since we are not pushing our grade to the array
using `array.push()`, we need to do a little bit of algebra
to add ourselves to the list */
return Math.round((sum + yourGrade) / (arrayLength + 1));
}
console.log(avg);
``````

## reduce

The `reduce()` method is quite similar to the `forEach()` method, but requires a lot less coding. :)

``````const yourGrade = 88;
87, 68, 94, 100, 83,
78, 85, 91, 76, 87
];