Rewriting JavaScript: Sum an Array

Chris Burgin
3 min readMar 5, 2017

A series covering how to rewrite common snippets of Javascript using function concepts. In this post we are going to cover how to find the sum of an array.

First, we will cover the standard method that you’ll recognize clearly. Even if you’re not a Javascript developer this example should ring a few bells.

The Standard Way

var numbers = [10, 20, 30, 40] // sums to 100
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i]
}

In The Standard Way we first declare the variable sum and set its initial value of zero. Next, we use a standard for loop to iterate through our array numbers and total up the array using sum. Simple, but not really the best solution.

One of the biggest problems with this snippet of code is that we introduce mutation into our code. In short, we created the variable sum whose value is changed at a later point. This is bad for readability as well as being more error prone than code which avoids mutation.

The Rewritten Way

Luckily Javascript provides us with ways to write immutable code, which I will demonstrate below. Changes are marked in bold.

const numbers = [10, 20, 30, 40] // sums to 100// function for adding two numbers. Easy!
const add = (a, b) =>
a + b

--

--

Chris Burgin

Christ follower. Dog caretaker. Developer at Generation Tux.