forEach return Cannot read property 'length' of undefined

Hi! I was trying to complete the " Basic Algorithm Scripting: Find the Longest Word in a String". This is my code:

function findLongestWordLength(str) {
  let words = str.split(' ');
  let max = 0;
  //console.log(word);
  words.forEach(function(word, index) {
      if (word[index].length > max) {
       max = word[index].length;
      }
    }
  )
  //console.log(max);
  return max;
  
}

console.log(findLongestWordLength("Google do a barrel roll"));

It returns Cannot read property 'length' of undefined.

Can anyone help me to figure out what’s wrong? Thanks in advance

Investigate what word is in your forEach. It’s not what you think it is.

word should be every element contained in the array words, right?

So if word is the individual word, what are you expecting word[index] to be?

1 Like

Oh, i got it. Now it looks a little dumb to me, but looking at some examples made my confused.

Thank you!

I’m glad I could help. Happy coding!