HELP Can't figure out my error :(

HELP Can't figure out my error :(
0.0 0

#1

So I am doing one of the algorithm challenges. i think I have a solution but I keep getting the error. “cannot read property length of undefined”

This is my code.


function findLongestWord(str) {
  
  arr=[""];
  arr=str.split(" ");
  var result = 1;
  
   for( i=0 ; i<= arr.length;i++){
     if(arr[i].length>= result){
       result=arr[i].length;
    }
    
   }
  
  return arr;
}

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

I have tried breaking it apart, but to no avail, Can anyone see where I am going wrong ?

Thanks in advance :slight_smile:


#2

This is actually a common problem when starting out. What happens is that you’re going through the for loop one time too many. You eventually reach a point where you try to compare arr[arr.length] which doesn’t exist because the length starts from 1 and the index starts at 0.


#3

cue epic face palm.

Hey man, thanks,

yeah that makes perfect sense, Just couldn’t see it.

Well one more noob error done and over with I guess.