Looping code - Learn web development | MDN

Let me try to give some explanations:
“After (contacts.length-1) iterations” means “When we enter the last iteration”. For example: Four contacts (contact.length: 4) need four iterations. Therefore contacts.length-1 is three. So “after three iterations” means we now enter the fourth and last iteration.
Now, if we are on our last iteration this means we haven’t found a match, yet. Otherwise we would have already left the loop because of the break statement. There are two possibilities:

  1. We find a match and break out of the loop
  2. We don’t find a match and need to write “Contact not found”

This sounds like we need to upgrade our if statement from 4.3. to an if...else statement, right? Inside the else part we set the paragraph text to “Contact not found”. Because we only want to set this text in the last iteration, we also need a if inside this else. In the end the structure looks something like this:

if(/* name is found */) {
  /* write text to paragraph */
  break;
} else if(/* it is the last iteration */) {
  /* write "Contact not found." to paragraph */ 
}

The last part of (5.) just means: “let the loop finish after we wrote ‘Contact not found.’ (no break needed)”.

I hope this clears it up a bit and didn’t make it more confusing :sweat_smile:
If you have any further questions, feel free to ask.

1 Like