Explain this JS code to me please

I have solved the challenge but I want to understand this code

function findLongestWordLength(str) {
let longestLength = 0;
let currentLength = 0;

for (let i = 0; i < str.length; i++) {
  if (str[i] === " ") {
    if (currentLength > longestLength) {
      longestLength = currentLength;
    }
    currentLength = 0;
  } else {
    currentLength++;
  }
}
if (currentLength > longestLength) {
  longestLength = currentLength;
}

return longestLength;
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");

My main question is how does the code knows that it compares a hole word and not just a latter

Rather then explain every line, could you let us know what is vexing you?

1 Like

Hi Kevin
My main question is how does the code know that it compares a whole word and not just a letter

You designed a solution, right? What was your big picture plan here? This code is executing that plan.

The heart of the loop handles work breaks.

I know that the loop handles work breaks, which is what I did in my solution, but in my solution, I used regex to break the sentence into an array of words (split can be used to do the same job ) in this code, it does the same functionality and it does not split the sentence I am missing out how the letters become words

Figuring out how code works is an important skill. Try logging stuff out and see if you can figure it out:

function findLongestWordLength(str) {
  let longestLength = 0;
  let currentLength = 0;

  for (let i = 0; i < str.length; i++) {
    console.log('*** loop', i, str[i])
    console.log('longestLength', longestLength)
    console.log('currentLength', currentLength)
    if (str[i] === " ") {
      if (currentLength > longestLength) {
        longestLength = currentLength;
      }
      currentLength = 0;
    } else {
      currentLength++;
    }
  }
  if (currentLength > longestLength) {
    longestLength = currentLength;
  }

  return longestLength;
}

console.log(findLongestWordLength("The quick brown fox jumped over the lazy dog"));

This is the magic part

@kevinSmith
ok, will do thank you Kevin

@JeremyLT
exactly the currentLength is reset to zero if not greater than longestLength and why does it contain a number of letters and not a single letters

Because the challenge only cares about the longest string (not the actual characters). longestLength is tracking the longest word’s length.

Current length is always set to zero when a space is found.

1 Like

@kevinSmith
Thank you so much Kevin Your code helped me understand, the debugging was so professional that it made every step clear to me.

@JeremyLT
Thank you very much, Jeremy, I can see that now if I could take two answers as the solution it would be both your’s and Kevin’s

This is a good problem for showing off that there is a variety of syntax that basically expresses the same logic.