Why does not using "break" return "contact not found"?

(Modestas) #1

Hi guys im on the “Looping code” section of learning JS through the MDN.

var contacts = [‘Chris:2232322’, ‘Sarah:3453456’, ‘Bill:7654322’, ‘Mary:9998769’, ‘Dianne:9384975’];
var para = document.querySelector(‘p’);
var input = document.querySelector(‘input’);
var btn = document.querySelector(‘button’);

In this example they talk about the break statement.

btn.addEventListener(‘click’, function() {
var searchName = input.value;
input.value = ‘’;
for (var i = 0; i < contacts.length; i++) {
var splitContact = contacts[i].split(’:’);
if (splitContact[0] === searchName) {
para.textContent = splitContact[0] + ''s number is ’ + splitContact[1] + ‘.’;
} else {
para.textContent = ‘Contact not found.’;

I just want to know why removing the break would always return " ‘Contact not found.’" even when the contact you search for exists, what is the logic behind this? Why would the lack of break statement cause the para.textContent = splitContact[0] + ''s number is ’ + splitContact[1] + ‘.’; code to be rendered useless even though its perfectly logical code?
Thank you!

(Baptiste Thémine) #2

Without break statement , the for loop will continue to compare searchName with contact names. As a result, if searchName is one of the contacts but not the last, the last iteration puts ‘Contact not found’ into para.textContent. I think this syntax is a little ugly and illogical, I never use break statement inside a loop. I prefer and it is more understandable to do it like this :

//Search the contact name
var result = contacts.find(function(contact){
    return (contact.split(’:’)[0]===searchName);
//If contact is found, puts number, else puts not found
    var splitContact = result.split(’:’);
    para.textContent = splitContact[0] + ''s number is ’ + splitContact[1] + ‘.’;
else para.textContent = ‘Contact not found.’;