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:
1 2 3 4 5 |
var str = 'this is a string'; var arrOfStr = str.split(' '); console.log(arrOfStr); ["this", "is", "a", "string"] |
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:
1 2 |
console.log(arrOfStr[0]); this |
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:
1 2 3 4 5 |
function findLongestWord(str) { return str.length; } findLongestWord("The quick brown fox jumped over the lazy dog"); |
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:
1 |
var wordArray = str.split(" "); |
We also need to create a variable to store the value representing the length of the longest word.
1 |
var wordLength = 0; |
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:
1 2 3 |
for (var i = 0; i < 5; i++){ //code here iterates 5 times } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function findLongestWord(str) { //split str into an array of words var wordArray = str.split(" "); //create var to hold length of longest word var wordLength = 0; //loop through each word in wordArray //if the length of the word is longer than previous longest word //store new longest word in wordLenght for (var i = 0; i < wordArray.length; i++){ if (wordArray[i].length > wordLength){ wordLength = wordArray[i].length; } } return wordLength; } |
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