Help: Find the Longest Word in a String

Why does my function return the length of the array and not just of the given index/string?
Console logs 9, but it should log 6.

  1. function findLongestWord(str) {

  2. str = str.split(’ ');

  3. var ind = 0;

  4. str.forEach(function(val){

  5. ind = val.length;

  6. if(ind < val.length){

  7.  str = val;
  8. }
  9. });

  10. return str.length;

  11. }

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

ind = val.length;
if(ind < val.length) {

The above if statement never evaluates to true, can you see why?

Now for some other criticisms:

What is ind meant to be keeping track of? The name suggests it’s an index of some form, but it’s storing the length of a word?

IMO you shouldn’t reassign str in a loop that traverses str, that’s much harder to reason about and is more bug prone than having another variable longestString or something.

As we’re only interested in the length of the words, you don’t need to keep track of the longest string anyway. Perhaps you should modify your forEach function to specifically keep track of the maximum length more clearly and then simply return that.

There are some higher order functions that make the code cleaner, after you’ve gotten this to work consider attempting a solution using map and reduce