Javascript: Find the Longest Word In A String

This exercise calls for an Algorithm that finds the longest word in a string input and outputs the length of that string.

Below is my solution:

function findLongestWord(str) {

var SplitString = str.split(‘ ‘);
var largest = 0;
for (var i = 0; i < SplitString.length; i++) {
if (SplitString[i].length > largest) {
largest = SplitString[i].length;
}
}
return largest;
}

findLongestWord(“The quick brown fox jumped over the lazy dog”);

Breakdown:

var SplitString = str.split(‘ ‘);

First, we take our sentence and create an array of each individual word in that sentence. The split function uses blank spaces to create the array elements.

var largest = 0;

Second, we create a variable called largest that will initially be set to 0, only because each time we perform a loop we will check to see if the current array item is bigger than the previous item. As a starting point of course each word will have a non zero length.

 

for (var i = 0; i < SplitString.length; i++) {

Third, this is the start of our loop, and essentially says we will start at 0, and ensure that every item is looped through. For example, if our array was “1”, “2”, “3”. 1 is at index 0, 2 is at index 1, and 3 is at index 2. The array length is 3. When the loop reaches 2, it would add 1 to 2 making it 3, and thus the loop would stop, because it is no longer less than the length.

 

if (SplitString[i].length > largest) {

largest = SplitString[i].length;
}

Everytime there is a loop, the loop checks the items at that current index and checks to see that it is larger than the variable “largest“.

In the first loop, largest would become whatever the item is at index[0] only because whatever word is there would have a length greater than 0. The loop would perform another iteration keeping the value of largest stored, and then check to see if the word’s length at that indexed location would be greater than whatever the previous value was. After the loop has finished iterating, we will have the length of the largest string, and this will be stored in the variable largest.

 

return largest;

Lastly, we just need to output the variable largest, which is our longest string in the array, thus solving the problem.