find the average of all elements in an array in javascript

To find the average of all elements in an array in JavaScript, you can use a loop to iterate through each element of the array and calculate the sum of all elements. Then, you can divide the sum by the total number of elements in the array to get the average.

Here's an example code snippet:

index.tsx
// define an array
const myArray = [1, 2, 3, 4, 5];

// initialize a variable to store the sum
let sum = 0;

// use a loop to iterate through each element in the array and calculate the sum
for(let i = 0; i < myArray.length; i++){
  sum += myArray[i];
}

// calculate the average by dividing the sum by the number of elements in the array
const avg = sum / myArray.length;

console.log(`The average of all elements in the array is ${avg}`);
441 chars
16 lines

This will output:

index.tsx
The average of all elements in the array is 3
46 chars
2 lines

Note: The reduce() function in JavaScript can also be used to calculate the sum of all elements in an array and simplify the code further.

gistlibby LogSnag