For-loop with <=

Hi there!
This from the code of challenge 210 “Profile Lookup”, of which the discussion was closed recently.
There is a standard solution, looking like this:

 for ( i =0; i< contacts.length; i++){
   if (firstName===contacts[i].firstName) {
     if (contacts[i].hasOwnProperty(prop)) {
       return contacts[i][prop];
     } else {
       return "No such property";
     }
   }
 }
  return "No such contact"; 

And there was my solution, looking like this:

 for ( i =0; i<= contacts.length; i++){
   if (firstName===contacts[i].firstName) {
     if (contacts[i].hasOwnProperty(prop)) {
       return contacts[i][prop];
     } else {
       return "No such property";
     }
   }
 }
  return "No such contact";

You’ll notice that the only difference between those two is in the following lines:
1.for ( i =0; i< contacts.length; i++){
2.for ( i =0; i<= contacts.length; i++){

In the second I used “<=” instead of a plain “<”. This resulted in an Error “TypeError : Cannot read property 'fristName of undefined”

I don’t understand why my code shouldn’t work, or why it resulted in a TypeError.
Any help or explanation will be greatly appreciated!

here contacts.length=4;
for ( i =0; i< contacts.length; i++){ the for loop iterates from i=0 to i<4 where

i=0 1st object
i=1 2nd object
i=2 3rd object
i=3 4th object
i=4 exit condition reached 

but when you do for ( i =0; i<= contacts.length; i++){ loop iterates from i=0 to i<=4

i=0 1st object
i=1 2nd object
i=2 3rd object
i=3 4th object
i=4 5th object(which does not exist hence it is taken to be undefined and you are trying to read the first name of an object that does not even exist hence the error)
i=5 exit  
1 Like

Ahh! Now I understand!
Thanks, man! :grin:

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.