Longest Word in a String : For Loop and If condition not enough ?!

Tell us what’s happening:
What do you think ? What’s wrong ? I was thinking that using for loop and if condition is enough to check all the cases
image
Your code so far


function findLongestWordLength(str) {
const arr = str.split(" ");
console.log(arr)

let longmax = 0;

for (let i = 0 ; i < arr.length -1 ; i++){

  if (arr[i].length  > arr[i+1].length){
    longmax = arr[i].length;
   
  }else if(arr[i].length <= arr[i+1].length){
   longmax = arr[i+1].length;
  }
}
return longmax;

}

findLongestWordLength("The quick brown fox jumped over the lazy dog");
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/89.0.4389.72 Safari/537.36 Edg/89.0.774.45.

Challenge: Find the Longest Word in a String

Link to the challenge:

On the for loop you are using arr.length - 1, when you should simply be using arr.length

This is because you’re also using < and not <=, so if the length is 5 then it’ll be i < 4, meaning i will only go to 3.

You just need to switch i < arr.length - 1 to i <= arr.length - 1 or i < arr.length, the latter being the most used out of the two.

1 Like

you are always confronting two consecutive words in the string and picking the longest, which means that at the end you get the length of the longest between the last two words, not in general
you are doing the equivalent of

if (arr[arr.length-2].length > arr[arr.length-1].length) {
   return arr[arr.length-2].length;
} else {
   return arr[arr.length-1].length;
]

maybe you need to do something more with longmax


that is correct actually, otherwise arr[i+1] goes out of bounds, making stuff not work as intended, the error is not there

1 Like

I see thank you tones :grin: