[SOLVED] Issue with "Find the Longest Word in a String" array length in if statement

I’m having some problems figuring out the issue with my solution. I’m getting an error related to the if statement, specifically to the part str[i].length

The error saying TypeError cannot read property ‘length’ of undefined

If i just do a “return str[i].length;” outside of the if statement, it outputs just fine…so I don’t get why it’s not working in the if statement.

function findLongestWord(str) {
  str = str.split(" ");
  var stringLength = str[0].length;  // = 4
  for (var i = 1; i <= str.length; i++) {  // runs 10 times
    if (str[i].length > stringLength) { 
      stringLength = str[i].length;
  return stringLength;

findLongestWord("What is the average airspeed velocity of an unladen swallow");

It is giving an error for the last “turn” of the for loop. You are looping from 1 to the string length. So, i gets the values 1 … 10 (In this example). But the indexes of str start from 0. So instead of 1 … 10, you should loop from 0 … 9.

1 Like

That did the trick and makes complete sense, thank you!