Return is exiting my for loop even outside the loop

I have a loop that is supposed to go through and compare the length of every item in an array and change the wordLength variable if it is larger the problem is that my return is exiting the loop after only one go through even though i am executing the return outside the loop. why is this happening???

function findLongestWord(str) {
  
  var arr = str.split(" ");
  var wordLength = 0;
  
  for(var i = 0; i < arr.length; i++){
    if(wordLength < arr[i].length){
      wordlength = arr[i].length;
    }
  }
  
  return wordlength;
}

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

It’s not the return statement that’s causing problems. You’re using 2 different variables, likely due to a typo!

You declare wordLength at the beginning, and you use it in the if statement, but you assign arr[i].length to wordlength instead of wordLength.

Once you fix that, your program works great.

2 Likes

Thank you sooner or later i will get past these rookie details

I’ve been doing this for awhile, and I still make mistakes exactly like this one.

One thing to look forward to, though, is when you start coding on your own machine, you can use things like ESLint to help catch these mistakes as soon as you make them. Keep going!

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

Yeah, I make those mistakes too, all the time too. It’s easy to do. Some editors will put variables that haven’t been declared in another color. I’ve gotten better at catching them by figuring out the color codes of various editors.