Need Help Understanding why this function works

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 :slight_smile:

Your code so far

function findLongestWordLength(str) {
var words = str.split(' ');
var maxLength = 0;


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:

maxLength starts as 0 indeed, but what happens after the first iteration loop is executed (with i = 0) and condition is checked?

1 Like

maybe this will help you to understand the flow of the iteration

1 Like

This condition gets evaluated only if the word length is greater than maxLength.
(Note that maxLength is not static, its value can be reassigned or changed)
This change of value will keep happening till we reach the longest word i.e. ‘jumped’ and maxLength gets assigned a value of 6.

After that, the condition never returns true and hence the value doesn’t change, and after the loop completion, you get returned the max length.

Any doubts are welcome!

Thank you I believe I understand the function now after your reply and jaswindersbm reply below.

ok I get it, after reading your reply and sanitys above I think I understand, so the maxLength = 0 is being reassigned everytime in the loop as long as it is true. I was looking at maxLength = 0 as being a static 0 and never changing. Thank you guys for the quick replies!

1 Like