Rewriting JavaScript: Sum an Array
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
The first thing to note is that we changed numbers from a
var
to a const
. We want to make sure that numbers is a constant; it’s not going to change. For more on const and let, see this fantastic article by Mozilla.Next, you will notice that we added a function called
add
. This function simply takes two numbers and adds them together. If you have not seen this syntax before I recommend checking out this MDN page on Arrow Functions.Next, we will write the segment that adds our array.
const numbers = [10, 20, 30, 40] // sums to 100
// function for adding two numbers. Easy!
const add = (a, b) =>
a + b
// use reduce to sum our array
const sum = numbers.reduce(add)
One line, and we’re done. Working from left to right notice that we set the variable
sum
as a constant. Once this variable is set we do not want it changing as that would introduce mutation.Next, you will notice that we execute the method
reduce
on numbers, and set it to the variable sum
eliminating the need for mutation. The reduce method accepts a function that takes 4 arguments. In our case, we only need the first two. The first two arguments are as follows.accumulator
— The value returned from the last callback.currentValue
— The current element being processed in the array.
Because we give reduce the function
add
, the values accumulator
and currentValue
get mapped to a
and b
in our add function
respectively.For more clarity of what is happening, let’s break it down step by step for each value in our array as it is processed by the reduce statement.
First Iteration: In the first iteration of the array the values are as follows:
accumulator = 10
and currentValue = 20
added together we return 30
.Second Iteration: In the second iteration of the array the values are as follows:
accumulator = 30
and currentValue = 30
added together we return 60
.Third Iteration: In the third iteration of the array the values are as follow:
accumulator = 60
and currentValue = 40
added together we return 100
.As you can see in each of this iterations, the
accumulator
is the value returned by each execution. Once you break it down, the reduce method becomes quite simple to understand. Check out the MDN article on reducers for more info. I highly suggest you read it carefully to understand what else reduce has to offer.The Wrap
By replacing the standard loop with reduce, we have removed the mutation from our code, allowing for cleaner, easier to read code that will benefit us as our application grows.
I’ll be covering more topics in the near future about rewriting basic Javascript concepts using the new standards. Until then I suggest you take a look at the useful readings below for more info on the above topics.
Read More Articles
0 Comments:
Posting Komentar