For Loops vs. forEach()

I recently wrote a post here at Crooked Code discussing that, as a relative beginner to JavaScript, I’ve had a tendency to use loops exclusively when traversing an array.

Further, I wondered if it would be better if I were taking advantage of the methods built into the array prototype. Methods such as forEach(), reduce(), map() and filter().

Let’s take a look…

For reference, MDN is a great resource to learn more about arrays and the array prototype.  They cover forEach() in far greater detail than I will here, so I encourage you to go read it.

How do you use forEach()?

Simply put, forEach() takes a callback function as an argument and executes that function on each element of the calling array.

The callback function takes 3 arguments – the element value, the element index and the array being traversed.  Instances where the index and array are not needed in the callback function, you’ll see it invoked with only the element value.

A simple example of forEach():

 

When should I use forEach vs. a for loop?

Researching the differences between a for loop and forEach() to write this post has been somewhat enlightening (there are some very opinionated people out there).

First, if you need to stop or break out of the loop before every element is visited, forEach() is not the right function.  In such cases, use a for loop, or look into using every() or some().

Other than that, it seems to come down to performance vs. readability.

Improved Readability with forEach()

Let’s revisit the example above and compare the same functionality using a for loop.

I’ll let you be the judge as to which one is more readable…

Personally, I think the more you use forEach(), the more you’ll prefer it to a for loop for readability.  Clearly, not using additional variables or worrying about ‘off by one errors’ is an added benefit too.

It’s also worth mentioning that ES6 syntax, with the arrow function, improves the readability even further.  I’m still writing my functions the archaic way, which is what I did above, but the same function written in ES6 would look something like this:

Performance

I used jsperf to run performance tests to compare for loops, while loops and forEach().  The tests were run in the Chrome browser.

The for and while loops were the clear winners (6,233 and 6,261 Ops/sec respectively).  forEach() was 18% slower at 5,202 Ops/sec.

So, on a sheer performance basis, the loops were faster than the function call to forEach().  I was a little surprised, however, that forEach() was only 18% slower than the loops.

Bottom Line…

I think you could argue either way of which one, the for loop or forEach(), is better.  Ultimately, I think it depends on the use case…

If you’re developing something that is very data intensive, and the extra performance of the for loop will make a difference, go with the for loop.

Otherwise, if you find forEach() to be more readable and aren’t iterating over huge data sets, use forEach()…

Either way, get out there and build something cool…  That’s it for now, see you next time.

-Jeremy

Side Note

Finally, I need to mention that the forEach() method takes an optional second argument that provides the value to use as this when executing the callback.

Covering this in depth was beyond the scope of this blog post, but You Don’t Know JavaScript: this & Object Prototypes Ch. 2 has an excellent, easy to understand example of using the this argument.

When all you have is a hammer, everything looks like a nail…

I recently posted about an overly elaborate solution that I wrote to a CodeWars algorithm. That post has been lurking in the back of my head since I wrote it…

I’ve come to realize that I can’t be too hard on myself for coming up with the solution that I did.  After all, the only tool I had available to me was a hammer, so I treated every problem like a nail.

Man Hammering Nail
An image of me writing code

My point is that up until then, any time I had to traverse an array, I had used a for loop rather than any of the methods native to the array prototype.  Setting the conditions of the loop to something like (var i = 0; i < arr.length; i++) allows you to easily access and manipulate any element of the array using arr[i].  So that’s what I did…

While there’s (usually) nothing inherently wrong with that (in fact, it’s how I solved many of the algorithm challenges at Free Code Camp), loops aren’t always the most elegant solution to a problem, especially when you start to consider asynchronous options in your code.  Besides, the point of this journey is to become the strongest developer I can, so let’s explore other options.

While going through the front end program at Free Code Camp, I was exposed to many of the methods in the array prototype, including forEach(), reduce(), map() and filter().  The problem was that those methods required callback functions, of which my understanding was tenuous, so I found it much easier at the time to use loops.

Working with Node.js these past few months has given me much more exposure using callback functions, so I’d like to revisit these methods and solidify my understanding of them.  That way, when I encounter problems in the future, I’ll have more than one tool at my disposal.

Over the next couple weeks, I will write a post that will cover each of the four array methods mentioned above in detail.  Hopefully, these posts will serve as good resources for others in my position and, at the same time, give me extra practice using each.

I’ll be sure to come back and provide links to the follow up posts once they’re written.

That’s it for now, thanks for reading.

-Jeremy

FCC Intermediate Algorithm Scripting Challenge – ‘DNA Pairing’

 

Today, we’ll cover freeCodeCamp’s Intermediate Scripting Challenge ‘DNA Pairing‘.  The challenge here is to write a function that accepts a string of characters and returns a 2D array of matched base pairs.

If you’re not caught up with your molecular biology, here’s a quick lesson…

Molecular Bio 101 (mostly not needed to solve algorithm)

By Zephyris at the English language Wikipedia, CC BY-SA 3.0
By Zephyris at the English language Wikipedia, CC BY-SA 3.0

DNA is the double stranded nucleic acid that carries your genetic information.  Each single strand is composed of units called nucleotides, of which, there are four – cytosine (C), guanine (G), adenine (A) and thymine (T).  In double stranded DNA, these nucleotides bond in specific base pairs, A with T and C with G.

DNA stores all kinds of biological information and make up our chromosomes, which, in turn, make you who you are…  Enough bio, let’s get back to solving the algorithm….

Bio Class Dismissed…

As we get into the intermediate and advanced algorithm challenges, each challenge will have multiple (even many) approaches to a solution.  My plan with Crooked Code is to explain the solution that I used, then search for solutions used by others in order to illustrate the various ways an algorithm can be written.

This is what freeCodeCamp gives us as a starting point for ‘DNA Pairing’:

The instructions provided for this challenge tell us that we’ll be getting a string as an argument and we must return a 2D array that matches up each element (letter) with it’s base pair counterpart.

Let’s get started working on a solution…

I started by ‘splitting’ the string argument into an array using string.split() method.  I covered string.split() in depth here.   I also created some variables that we’ll use later in the function.  My ‘pairElement’ function now looks like:

We now must scroll through ‘singleArr’ and pair up each element with it’s matching pair.  We can use a for loop to scroll through the array, but how can we match up the pairs?

A bunch of if/else statements would work but a switch statement is a better option here.  A switch statement will evaluate a given expression, then transfer control to the case that matches the outcome of the expression.

I’ve included the syntax of a switch statement written by mozilla in order to make the explanation easier.

In our case, the expression will be just a letter, as will each case value.  We can then write a statement to be executed for each individual case.

To sum up the logic for our algorithm…

  • split the given string into an array
  • loop through array and match each element with it’s pair
  • ‘push’ each new pair into 2D array
  • return 2D array

At this point, we’ve covered everything needed to solve the ‘pairElement’ function.  If you’re working through the freeCodeCamp curriculum you may want to go try to solve it on your own, otherwise, read on…

Spoilers_ahead

Here’s the solution to the ‘DNA Pairing’ challenge that I came up with:

The freeCodeCamp wiki page (written by @Rafase282 and @sabahang) provides 2 solutions to this algorithm challenge.  The first, ‘basic’, solution is very similar to mine, using a switch statement, so I won’t include it for the sake of redundancy.

The second, ‘intermediate’, solution uses an object, and we haven’t really covered objects in much detail here at Crooked Code.  I’ll include the code below so we can see a second, very different solution, but won’t provide an explanation, as objects are far too big of a topic to cover at the end of this post.

You can see an explanation to this solution at the wiki page.

That’s it for now, hopefully this helped straighten out the code…

-Jeremy

FCC ‘Find the Longest Word in a String’

The next freeCodeCamp algorithm that we’ll work on here at The Crooked Code will be ‘Find the Longest Word in a String’.  The challenge here is to write a function that accepts a string as a parameter and returns the length of the longest word in the string, which means we’ll be returning a number.

Before we start on the algorithm, there are a few JavaScript concepts that we’ll need to go over…

In JavaScript, methods are functions that are stored as object properties. Further, there are many methods that are built into JavaScript that are available to manipulate things like strings and arrays.  This algorithm will let us start exploring the methods associated with these various data types.  This concept might not seem immediately clear, however, this w3schools page explains the concept in a little more detail, or just keep reading this post and things should clear up.

As is the case with accessing other properties of objects, we can use dot notation to call these methods.

Let’s try to clear things up with an example:

String.split() is one of many methods that can be used on a string.  Split() will divide a string into an array of substrings.  It takes up to two arguments.  The first argument is the separator, or where the string will be divided.  The second argument is the limit and is optional.  The limit is a number specifying the max number of substrings (we won’t be using this second argument is this example).  In use, split() looks something like this:

A few things to note in this code…  We passed (‘ ‘) to str.split which means str will be divided into substrings at each whitespace.  (if you pass (”) str will be split at every letter, if you pass ‘,’ it’ll be split at every comma and so on..).    Also, console.log() is an excellent way of checking that your code is doing what you want.  In this case, we passed it the array of strings (arrOfStr) in which we stored all the substrings so we could check if the code was doing what we intended.  As you can see from the line below the console.log call, arrOfStr now contains 4 different strings, 1 for each word in the original string (str).

One more quick thing to cover before we get into solving the algorithm – arrays.  An array is a data structure that allows us to store a list of multiple values in a single variable.  Each value in the list is called an element and can be accessed individually using bracket notation, which is also explained in this MDN page.  An example using bracket notation with the above example would be:

As you can see, the index (the number inside the bracket notation that accesses an individual element in the array) of the first element of an array is 0.  Therefore, when we log index 0 of arrOfStr to the console we get ‘this’.  A good intro to arrays can be found here.

Ok, now moving onto the problem at hand…

FCC provides the following starting point:

We need to write the code inside the findLongestWord function that will return the length of the longest word.  FCC then starts to check your code by calling findLongestWord with the string ‘The quick brown fox jumped over the lazy dog’.

We can start by splitting the original string into an array of individual words as such:

We also need to create a variable to store the value representing the length of the longest word.

Now we need to write a loop to go through wordArray and look for the longest word.  Something to help with both these tasks is the method .length which can be used on both strings and arrays.  String.length will return the number of characters in a string.  Array.length will return the number of elements in an array.

A for loop is an easy way to iterate through an array.  The for loop is different from the while loop used in the last algorithm in that it is initiated using three statements.  A decent intro to a for loop can be found here but I’ll try to use an example to illustrate how it works:

The first statement (var i = 0;) executes before the loop begins.  In this case, we initialize a variable (i) to equal 0.  The second statement (i < 5) is the condition that must remain true for the loop to continue.  In this case, the loop will iterate 5 times (while i is equal to 0 through 4).  The third statement is executed at the end of each iteration, in this case, i is incremented by 1 each time.

Combining everything we’ve discussed thus far to solve the algorithm:

The comments in the code ( everything following //) should help you follow the logic.  The only thing in the code that we didn’t cover previously is the if statement.  The code is fairly self explanatory, but you can read up on if statements on this MDN page.   Basically, if the statement inside the () of an if statement is true, the code following (either a single line or a block inside {}) is executed.  In this function, the if statement is used to check if the current word is longer than the previous longest word.  If true, the length of the new longest word is stored in wordLength.

Hopefully this straightened out the code for you.  See you next time.

-Jeremy