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 ‘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