Find the Longest Word in a String using Reduce

Can anyone explain why does my code not work? I can get it to log "jumped’ if I type “return prev” instead of “return prev.length” but I can’t get it to log 6.

function findLongestWord(str) {
return str.split(’ ').reduce(function (prev, curr) {
if (prev.length > curr.length) {
return prev.length;
} else {
return curr.length;
}
});
}

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

The first time the reduce function runs, prev is a string and has a .length property. But you return a number and prev becomes that number.

The next iteration of reduce is run and you try to get the value of prev.length - that’s a string property, not a number property.

If you stick to returning strings and then, when reduce is done, return the length of the reduce result, it should work fine.

~Micheal

2 Likes

The issue is that when you return prev.length you are returning a number. Javascript evaluates the number then as a string, with a length of one.

EDIT: Ah, beaten to the punch!

2 Likes

okay, gotcha. That makes sense.

Thanks!