Write a JavaScript program to find the sum and average of array elements

Description: Find the sum and the average of the array [10, 20, 30, 40].

Hint:

  • Use reduce() to add all items.
  • Average = sum / number of items.

JavaScript program for sum and average of an array

const numbers = [10, 20, 30, 40];

const sum = numbers.reduce((total, n) => total + n, 0);
const average = sum / numbers.length;

console.log("Sum:", sum);
console.log("Average:", average);

Output:

Tutorials Class - Output Window

Sum: 100
Average: 25

How it works

  • reduce() starts with 0 and adds each number.
  • The average is the sum divided by numbers.length.

Read Array Methods.


Learn more about the similar topics:
Tutorials
JavaScript Arrays
JavaScript Array Methods
JavaScript Objects
Exercises & Assignments
Write a JavaScript program to find the sum and average of array elements
Write a JavaScript program to find the largest and smallest number in an array
Write a JavaScript program to remove duplicates from an array
Write a JavaScript program to filter even numbers and double them
Write a JavaScript program to count the frequency of words in a sentence
Interview Questions & Answers
What is the difference between map and forEach?
What is the difference between slice and splice?
What is the difference between shallow copy and deep copy in JavaScript?
What is the difference between spread and rest operators?
What are Map and Set in JavaScript?
How do you check if a variable is an array in JavaScript?