Longest word in a string check my code

Tell us what’s happening:

So In my code the look for longest words and logic is to save the str to an array named words. Compare each word length in words array for the greater length. save the greats number to size and then return the size once the for loop is completed.

Your code so far


function findLongestWordLength(str) {
const words = str.split(' ');
//console.log(words);
let size =0;
for ( let i = 0; i<=words.length;i++) {
   //console.log(words, words[i].length);
   if (size > words[i].length) {
     console.log(words[i], words[i].length)
     size = words[i].length;
   } return size;
}
return size;
}

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/85.0.4183.83 Safari/537.36.

Challenge: Find the Longest Word in a String

Link to the challenge:

Please think this part over again and fix it.

const words = str.split(’ ');

//console.log(words);

let size = 0;

for ( let i = 0; i<=words.length;i++) {

 //console.log(size, words[i].length);

 if (size < words[i].length) {

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

   size = words[i].length;

 } 

} return size;

}

findLongestWordLength(“The quick brown fox jumped over the lazy dog”);
the console looks like this and failing all tests. /
The 3
quick 5
jumped 6
TypeError: Cannot read property ‘length’ of undefined

thanks for speedy response. :slight_smile:

1 Like