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.
- For each object inside the
phonebook
array, it checks whether that object’sname
property is equal to the name you are searching for. - If it is, the paragraph’s content is changed so that it gives you the name, and the corresponding number.
- At this point, we stop looping using the
break
function. - 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 nameMustafa
, after each subsequent loop iteration would change the paragraph text toContact 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