Basic Algorithm Scripting - Find the Longest Word in a String

Tell us what’s happening:
I found this solution more explanatory till i got maxLength = words[i].length; My question is that how did maxLength discovered the longest word in the sentence and was able to return the value of 6 which is truely the length of the longest word “jumped”? If you remove the .length, i.e maxLength = words[i], and u log maxLength to the console, the console will return “The” which is a 3 letter word. I hope i am able to convey my message clearly.

Your code so far

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

  for (let 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/115.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Find the Longest Word in a String

Link to the challenge:

You are getting the length of the string from words[i].length, e.g. 3 or 4 or 5 or 6.
Then you are comparing which is bigger and store it into maxLength variable.

Try console them out:

console.log(maxLength, words[i], words[i].length)
image

Thanks, but this doesn’t answer my question sir/ma. Pls I need more replies. my question is that I want to know how maxLenght or words[i].length got to know which of the words from the sentence has the longest length.

I would skip trying to decipher this answer. The answer itself isn’t really useful. The practice coming up with a solution is more important.

I think this solution has syntax that you don’t understand. I’d try to write your own with syntax you are more comfortable with.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.