OneBite.Dev - Coding blog in a bite size

find the average of all elements in an array in Javascript

Code snippet on how to find the average of all elements in an array in Javascript

  var arr = [1, 2, 3, 4]
  var sum = 0;
  for (var i = 0; i < arr.length; i++) {
    sum += arr[i];
  }
  var avg = sum / arr.length;
  console.log(avg);

This code finds the average of all elements in an array. First, we create an array variable called ‘arr’ with the elements we want to average. We also create a variable called ‘sum’ and set it to 0. We then use a for loop to iterate through the elements in the array and add them to the ‘sum’ variable. After the for loop has completed, we divide the sum by the length of the array to get the average. Finally, we use the console.log() function to print out the average.

javascript