"Find the Longest Word in a String". Help

Why does the solution below not work?

function findLongestWord(str) {
str.split(" ");
var longest = str[0];
for (var i = 1; i < str.length; i++) {
if (longest.length < str[i].length) {
longest = str[i];
}
}
return longest.length;
}
findLongestWord(“The quick brown fox jumped over the lazy dog”);

.split returns an array, but you didn’t use a variable to hold onto that array. It’s the thing you want to iterate through in your loop.

You also don’t want to return the length of the longest word. You want the longest word itself instead. I’m wrong here, sorry :sweat_smile:

1 Like

Thank You. This was very helpful.

Oh, sorry I assumed that the challenge wants the word itself :sweat:

1 Like

SPOILER ALERT!
@taniatabz Your code really seems to show that you “get” how the loop works, even if you left a little out. :wink: So, I am wondering, have you tried using ‘map’? If you are use to using loops, it may seem weird at first to switch over… but once you get settled in… you will love using time savers like ‘map’, ‘reduce’, ‘filter’, ‘sort’, etc.

Any/all of those methods can be used on this problem to find a shorter and imho cleaner/easier to understand solution.

For any Newbies, it’s worth the time to learn these Array methods as well as how to use arrow functions.


has examples of all the Array methods mentioned.

Also, Math.max() and Math.min() can be a very useful tool when looking for the biggest or smallest number.

If we were dealing with an array of numbers vs. a string of letters, we could simply solve with: Math.max(…arr)

Since this is a string we need to:

  1. Math.max(), so our answer will find the max length.
  2. Rest (…) to make a copy of the str… which we turn into an array using split.
  3. Use map in lieu of a loop, to get the length of all values within our new array.

This all boils down to this single line of code:

Math.max(…str.split(" ").map(i => i.length));

Let me know if you have any more questions, and keep up the hard work!

1 Like