Tell us what’s happening:
So after trying some solutions myself for a while I finally decided to look up the solution to this problem but even after seeing the correct solution I’m still having a hard time understanding why the code below works. I’m mainly confused about whats happening in the for-loop. The specific part is the if-statement:
if (words[i].length > maxLength) { maxLength = words[i].length; }
I get that its checking to see if the word length is greater than the maxLength which is 0, but wouldn’t that return all the words in the array because they’re all greater than 0. I’m curious to know how the code knows to only find the longest word and not all the other words as well. If anyone can clarify it for me it would be gretly appreciated
Your code so far
function findLongestWordLength(str) {
var words = str.split(' ');
var maxLength = 0;
console.log(words);
for (var i = 0; i < words.length; i++) {
if (words[i].length > maxLength) {
maxLength = words[i].length;
}
}
return maxLength;
}
console.log (findLongestWordLength("The quick brown fox jumped over the lazy dog"));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36
.
Challenge: Find the Longest Word in a String
Link to the challenge: