Help for Test Skill: Loops 2

Hi there @ppirx, and well done on some great work here. This is example is just perfect, except that you need to remove the second break statement. To understand why, think about what code is doing.

  1. For each object inside the phonebook array, it checks whether that object’s name property is equal to the name you are searching for.
  2. If it is, the paragraph’s content is changed so that it gives you the name, and the corresponding number.
  3. At this point, we stop looping using the break function.
  4. If we didn’t break at that point, the loop would carry on checking all the other objects to see if their name was Mustafa. Since none of the other objects have the name Mustafa, after each subsequent loop iteration would change the paragraph text to Contact not found., making it look like the phone book doesn’t contain the name, when it actually does.

This is why the break statement is so important. Without it, the code would only work if Mustafa is the name in the very last object in the array.

Then think about why it doesn’t work if the 2nd break statement is left in the code. With it present, the code will break immediately after the first contact is search and the name is not found. So unless Mustafa is the name in the first contact, it won’t work.

Which brings me to the last small bug in the code — if you remove the object containing Mustafa, then the code will throw an error rather than informing you that the contact is not found. This is because your loop’s exit condition needs to be updated to i <= phonebook.length - 1.

Why? The original array has 8 objects in it, so a length value of 8. But with an exit condition of i <= phonebook.length, when the loop counts the i value goes through array indexes 0, 1, 2, 3, 4, 5, 6, 7, then 8 (remember that computers count from 0, so we had to start from 0 to count the first array item). But the highest array index value is actually 7, so therefore when it reaches 8 it will throw an error because array position 8 doesn’t exist.

So to count through all the array indexes without an error, we need to do i <= phonebook.length - 1

1 Like

oh! thank you very much @chrisdavidmills!! got it now

@ppirx you are most welcome.

I even realized that i could write …, i < phonebook.length… instead of i <= phonebook.length to avoid the iteration over to 8 positions which is wrong…as you mentioned. :wink:

ha, that’s even better :wink:

ahh I also forgot the “break”. thanks for this!