Javascript How to Sum an Array

Hello devs, today I'll show you how to sum an array. I'll show you two examples with that you can easily sum an array. So, let's see the examples below.  

Table of Contents

  1. Example 1
  2. Example 2

Example 1

In the first example, we'll use array.reduce() method to sum our array. Let's see the code snippet below

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const sum = arr.reduce((a, b) => a   b, 0);
console.log('The sum of array using for array reduce is = ' sum);

Which'll produce the below result.

Example 2

In this example, we'll use for loop to sum our array. Let's look at the below code snippet

let total = 0;
let len = arr.length;
for (let i = 0; i < len; i  ) {
   total  = arr[i];
console.log('The sum of array using for Loop is = ' total);

Which'll produce the same result which we get in #step1.

That's it for today. Hope this will be helpful for your future work. Thanks for reading. ๐Ÿ™‚