Find the longest word in a string. The force is not with me :(

This is quite disconcerting for me. The challenge consists in finding the longest word in a string, and as usual the program tests the function with a few different examples; my code works well in every case except for one, and I don’t know what’s different in it nor why it doesn’t work.

This is the code:

var longest=0;
function findLongestWord(str) {
var arr =str.split(" ");
for (var x = 0; x<arr.length; x++){
if (arr.length > longest) {
longest= arr.length;
}
}
return longest;
}

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

The code is tested with these strings:

“The quick brown fox jumped over the lazy dog” - It works

“Google do a barrel roll” - It works

“What is the average airspeed velocity of an unladen swallow” - It works

“What if we try a super-long word such as otorhinolaryngology” - It works

“May the force be with you” - It doesn’t work

Can anybody tell me what’s happening? Is my midiclorians level not high enough to pass the challenge?

You are not initializing longest every time you call the function.

Try to put var longest=0; inside the function.

2 Likes

Thank you, jenovs, now it works :slight_smile:

I assume that “May the force be with you” didn’t work because the program kept record of the longest word in previous strings; therefore, if “May the force be with you” would have been the first tested string it would have worked well as its longest word is the shortest among the rest. Am I right?

Yes, you are right…