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.
-
function findLongestWord(str) {
-
str = str.split(’ ');
-
var ind = 0;
-
str.forEach(function(val){
-
ind = val.length;
-
if(ind < val.length){
-
str = val;
-
}
-
});
-
-
return str.length;
-
}
-
-
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