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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.