my first question here: I was learning about loops from developer.mozzila.org and this was an example for 'break;' The user provides a name and this code searches through the array contacts and returns the number.
const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
const para = document.querySelector('p');
const input = document.querySelector('input');
const btn = document.querySelector('button');
btn.addEventListener('click', function() {
let searchName = input.value.toLowerCase();
input.value = '';
input.focus();
for (let i = 0; i < contacts.length; i++) {
let splitContact = contacts[i].split(':');
if (splitContact[0].toLowerCase() === searchName) {
para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
break;
} else {
para.textContent = 'Contact not found.';
}
}
});
I'm failing to understand how this code is not returning 'Contact not found.' on every iteration. Instead, according to MDN, it only does so if the name is not found in the array. Won't the code under 'else' execute every time the 'if' condition is not met?
Thanks and apologies if I'm missed some StackOverflow etiquette.