Find the Longest Word in a String problem with loop

Tell us what’s happening:
I don’t understand why it keeps returning 3?!

``````function findLongestWord(str) {
str = str.split(' ').join().split(',');
for (var i = 0; i < str.length; i++) {
return Math.max(str[i].length);
}

}

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

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36`.

https://www.freecodecamp.org/challenges/find-the-longest-word-in-a-string

The first word is “the”, math max of 3 is naturally 3, which you return, function completed.

Your function will end once it hits a `return` statement so you are only testing the first substring string of the array and then sending that length back as a result.

`str = str.split(' ').join().split(',');`
works but is redundant. The first split will give you the array of substrings you wanted.

You’re almost there. Good luck.

So a few things here:

There are three common strategies for this:

1. Convert to array, sort by length, pick the largest (it’ll be at one end).
2. Convert to array, get all the lengths, get the max of those lengths.
3. Convert to array, loop through and keep track of current and previous length, update with the max of the two, return that max once loop complete.

I think you’re trying to do 2. Math max doesn’t do anything in your code because you’re getting the max of a single value, eg for length 3, the max is always 3: you only test one number at a time. You would normally put all the lengths in a new array, and when you’ve finished the loop, return the max of that. You need to return after the loop ends.