How do for loops actually work?

Im kinda confused how the profile lookup solution works
So this was my intial code

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

However the correct way of doing it is putting the return “No such contact” outside of the for loop. Could someone explain to be how the loop works in this instance because i was thinking how can the return be outside when the whole loop is already iterated and were out of it.

Your code looks like it should be part of a bigger function (otherwise, where are firstName and prop created?), which is probably why you used return. But @SkyC is right, any return exits the function (and the loop).

You’re better off assigning to variables and returning a result after the loop is complete… which has the added benefit of reducing your repeating code (return "No such property";)

Other than that, it looks like your loop is built properly. :slight_smile:

1 Like