cisal24
cisal24

Reputation: 1

The 'break' command in Loops

I'm a new JS Learner and I'd like to understand this :
When I try to remove the "break" command and search for a name like "Chris" always find that the "if" statement is skipped and get the response from The "else" statement!

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.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.';
    }
  }
});

P.S/ sorry for my bad English.

Upvotes: 0

Views: 68

Answers (1)

P.E. Jo&#235;ssel
P.E. Jo&#235;ssel

Reputation: 1443

Your if statement is not skipped, if you add a console.log() inside the if, it will log to the console if there is a match. It will however show 'Contact not found' in your paragraph because the loop will still run and the last run will not be a match. Try looking for 'Dianne', you will have a match.

Using a break in will make your code work but is not the most elegant way to do it. You could use a find function like this:

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.focus();
  
  const searchResult = contacts.find(contact => (
    contact.split(':')[0].toLowerCase() === searchName
  ));
  
  if (searchResult) {
    const contact = searchResult.split(':');
    para.textContent = contact[0] + '\'s number is ' + contact[1] + '.';
 } else {
   para.textContent = 'Contact not found.';
 }
});
<input type="text">
<button>Search</button>
<p></p>

Upvotes: 1

Related Questions