Longest Word in a String (length issue)

Hello Folks,

Apologies if this may be a silly question, but i seem to have issues with the 2nd length check on my code. I see the results are going well on the console, however the end result doesnt come out, because of error.

TypeError: Cannot read property ‘length’ of undefined

Could someone kindly point out why this length is causing problems?


function findLongestWordLength(str) {
  
var arr = str.split(" ");
var endArr = []

for (let i=0; i <= arr.length ;i++) {
  
  var value =arr[i].length;  //why is this length problematic?
  
  endArr.push(value);

  console.log(value,endArr)
  
}
 
  return Math.max(endArr);
}

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

//testing some options

var str="The quick brown fox jumped over the lazy dog";
var str2= ["ola","adeus"];
console.log(str.split(" ").length)

console.log(str2[1].length);

Hello PAB.

Think about what arr.length returns in the declaration of the for loop.

Hope this helps

Also,read about Math.max function, and what syntax should be used when checking the array

of numbers

Hi Sky020,

Thanks that helped, but why the “=” was an issue, i dont understand. The arr.length gives the number of elements in the array (this case 9)

Hi Nina1012, Thank you, that was very useful.

and what’s the element at index 9?

1 Like

Oh i see, you are right :slight_smile: