** TypeError: Cannot read property ‘length’ of undefined
shows error at if statement at wordsArray[i+1].length
why cant length of wordsArray[0+1]= wordsArray[1] cant be read?
**
Your code so far
function findLongestWordLength(str) {
let wordsArray = str.split(' ');
let maxWordlength=0;
for(var i=0; i<wordsArray.length; i++)
{
if(wordsArray[i].length>wordsArray[i+1].length)
{
maxWordlength=wordsArray[i].length;
}else{
maxWordlength=wordsArray[i+1].length;
}
}
return maxWordlength;
}
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/87.0.4280.88 Safari/537.36.
Notice it doesn’t say that specifically wordsArray[1].length can’t be read. Think about what i would be needed so wordsArray[i+1].length couldn’t be read and what would make function try to use such i.
What I’m trying to say is that wordsArray[i + 1].length will give the correct value for i = 0, and some other i values too. Until function reaches such i value that this will give error. Can you see what is causing that?
For a slightly more pointing to the correct direction, you may add line
console.log(wordsArray[i + 1].length)
inside of the for loop and check what is happening that way.
Maybe think about it in this way - you are using i + 1 because you want to compare i-nth word with (i + 1)-nth. Keeping this in mind with what should be compared last word of the sentence - specifically at the point when i value is the index of the last word?
i++ won’t work properly, because it increments i, resulting in i being incremented twice in total after one execution of for loop.
ok i get it… when last element comes it doesnot have last+1 elemnt so it throws error…
if try the logic in reverse comparing last to last-1 and decrementing the loop same problem there is no first-1 element?
when i hits wordsArray.length-1 i+1 will be wordsArray.length which isn’t a defined index.
second, wordsArray[i+1].length isn’t valid when both wordsArray[i].length and wordsArray[i+1].length aren’t the max length so it sets the max lenght into one of them, try changing wordsArray[i+1].length to something else, that would actually be compared to the max length