Longest Word in a String (Help Explaining My Code)

Here is my code:

function findLongestWord(str) {
  //split string
  var arr = str.split(' ');
  var longest = 0;
  //run through the array
  for(var i = 0; i < arr.length; i++) {
    var word = arr[i];
    //I think I got it! 
    var wordLength = word.length;
    if (wordLength > longest){
longest = wordLength;
  return longest;

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

It ran and it worked. I did this a week ago and did not include any comments. I was reviewing it and can’t seem to piece together how it works or why it works. I did it on the fly with a friend and now I can’t quite follow what is actually happening. Any help explaining or commenting it out would be greatly appreciated. I get lost at about the halfway point.

Instead of explaining how code you wrote works step by step, why don’t you tell us which part of the code you do not understand? Another suggestion is, if you do not understand the code you wrote, then add some console.log statements at various points in the code to see the value of any variables where you are confused as to their values.

Thanks randelldawson. I just had my “aha” moment. I figured it out. I was getting lost around the wordLength variable earlier, but I think I see it now. Still not quite sure why I had to create the var longest = 0 though. My friend helped me with that part and I can’t quite remember the explanation.

The reason you need to initialize longest to 0 in the above solution, is you have to have a starting point for the comparison in the following line:

if (wordLength > longest){

The shortest word would be a blank string, so anything longer than that would be the longest seen so far. Another approach, would have been to assign the length of the first word to longest like:

var longest = arr[0].length;

and then you would initialize i = 1 inside your for loop, to start at the 2nd element.

1 Like