Trying to get the length of elements in an array

I am working on the “find the longest word in the string” challenge. I’m not done but I am getting an error I don’t understand:

Type error: Cannot read property ‘length’ of undefined

Here is my code:

function findLongestWord(str) {
  var t = str.split(' ');
  var i =t.length;  
  for (i; i>0; i--){
      var len = t[i].length;

return t;

If I change variable ‘i’ on this line var len = t[i].length; to a number it will give me the length of that element. It doesn’t work with the variable. I am trying to get the length of each element in one array ‘t’ and store it in a new array ‘len’.

Thanks for your help.

In the first iteration of the for loop, i = 9. There are 9 words in the array called t. Arrays are zero-indexed, so if an array has a length of 3, the indexes of the array are 0, 1, 2.

When you try to reference an element of an array that does not exist, then you get undefined. and undefined does not have a length property (hence the error message).

See if this helps you.

1 Like

Thanks for the reply.

I appreciate the reply giving the tools for the answer and not just correcting my code. I actually learned something!