Error when length keyword is used to push lengths to an array. Pls help

Tell us what’s happening:
I am trying to create an array called lengths which will have all the lengths of the elements in the array new_str.
The problem is when I am trying to push each length to the lengths array it says
‘Cannot read property ‘length’ of undefined’.
PS : My plan is to use Math.max() inorder to find the maximum length.

Your code so far

function findLongestWordLength(str) {
var new_str = str.trim().split(" ");
var lengths = [];
for(var i=0; i <= new_str.length; i++){
lengths.push(new_str[i].length);
}
console.log(lengths);
}

findLongestWordLength("The quick brown fox jumped over the lazy dog");


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; ) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Find the Longest Word in a String

Link to the challenge:

Remember that arrays are zero-indexed. This means that the highest index would only ever be the length of the array minus one. Look at your for loop condition and see if you can figure out your mistake.

1 Like

Thank- you.

i <= new_str.length -1 

:sweat_smile: