JavaScript: Find the Sum of Elements in an Array

1. Introduction

The process of summing all the elements of an array is a common operation in data analysis and manipulation. In JavaScript, this task can be achieved in several ways, but the reduce() method provides one of the most concise solutions. In this article, we'll dive into how you can compute the sum of an array's elements using JavaScript.

2. Program Overview

Throughout this guide, we will:

1. Declare an array of numbers.

2. Use the array's reduce() method to compute the sum of its elements.

3. Display the calculated sum.

3. Code Program

let numbers = [34, 2, 56, 7, 9, 21, 5];  // Array of numbers
let sum;  // Variable to store the sum of numbers

// Utilizing the reduce() method to find the sum of the array
sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log("Array:", numbers);
console.log("Sum of Elements:", sum);

Output:

Array: [34, 2, 56, 7, 9, 21, 5]
Sum of Elements: 134

4. Step By Step Explanation

1. Array Initialization: We kick off by declaring an array numbers containing various numeric values.

2. Using the reduce() method

The reduce() method processes each element of the array with a function, reducing its content to a single value. 

It takes two arguments: a reducer function and an initial value. In our case, the reducer function sums the accumulator (which keeps the running total) and the currentValue (which is the current element of the array). We've set the initial value to 0.

3. Storing and Displaying the Outcome: The derived sum is saved in the sum variable. We then use console.log to show both the original array and the computed sum.

Comments