I don't understand the issue here

Tell us what’s happening:
“TypeError: Cannot read property ‘length’ of undefined”

I can’t figure out what I’ve done wrong. It seems like this code should be the correct way to do it, but for the life of me I dont’ see what I’m doing wrong to have broken .length

Your code so far


function findLongestWordLength(str)
{
var splitStr = str.split(' ');
var max = 0;
for(var i = 0; i <= splitStr.length; i++)
{
  if(splitStr[i].length>max)
  {
    max = splitStr[i].length;
  }
}
return max;
}

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.

Challenge: Find the Longest Word in a String

Link to the challenge:

Hi and welcome to the forum!

It looks like you have an off by one error here. JavaScript is zero indexed, so a 5 element array has indices
[0, 1, 2, 3, 4]

Edit: This means that element 5 would be undefined and thus not be a string with a ‘length’ property.

1 Like

Same answer as JeremyLT, but with a bit more context if needed. The only thing it cannot read is splitStr[i] with i being equal to 9, since the last element of the array you defined would be at index position 8 because it starts at 0.

Everything else should be fine

2 Likes

Yep, ya’ll called it. Appreciate it.

1 Like