Javascript loop

Hi~

i was checking out loops tutorial and practising this code I have doubt here that in else if() the condition is

else if(i === contacts.length - 1) 
contacts.length - 1 

// why will it output "contact not found" when the contact does not exists in the array?

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 if (i === contacts.length - 1) {
      para.textContent = 'Contact not found.';
    }
  }
});

Thanks!

Hello,

I’m not sure I’m understanding the question. Do you have doubt that the logic is correct? Or do you have doubt about the reasons why this works?

Anyway, The logic of the conditions in the for loop is as follows:
1- Check each individual name in each element of the array against the searched word.
2- If they match, output the element’s index and break from the loop.
3- In case they don’t match, and we are at the last element of the array (that’s the reason for the check i === contacts.length - 1), put out “contact not found”. Because that was the last element of the array that we search and if this element is not the one we seek, that element does not exist.

Hope that helps.

2 Likes

Yep I want to know how this works

Thanks for replying!

I want to request you that can u please elaborate 3. Point

Thanks again

I’d say this is a poorly constructed loop. The else if part

 } else if (i === contacts.length - 1) {
      para.textContent = 'Contact not found.';
 }

is simply checking if the current i is the last element or not. So we’re saying

for all elements of the array {
  if this element is a match {
     set reply to this person's number
} else if (if this element is the last element) {
    set reply to not found
}

We can and need to avoid this kind is this the last element? for every element inside the loop.

Assuming there will be at most one match, then we can rewrite the function like this

for (all elements of the array) {
  if the element is a match {
    set the 'found' reply 
    return
  }
}
set the reply to not found
return
 for (let i = 0; i < contacts.length; i++) {
    const  splitContact = contacts[i].split(':');
    if (splitContact[0].toLowerCase() === searchName) {
      para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
      return;
    }
  }
//if we reach here, it means no match was found 
//(if we found it then we returned from function already)
 para.textContent = 'Contact not found.';
return; //this statement is optional

We can improve the readability by using destructuring assignment

 for (let i = 0; i < contacts.length; i++) {
    const [name, number] = contacts[i].split(':');
    if (name.toLowerCase() === searchName) {
      para.textContent = name + '\'s number is ' + number + '.';
      return;
    }
  }
//if we reach here, it means no match was found 
//(if we found it then we returned from function already)
 para.textContent = 'Contact not found.';
1 Like

Let’s go through a practical example:

Suppose you have a hand of cards that lacks one or more cards (like king of hearts, 10 of diamonds, etc.).
Now, you are given a card, say queen of diamonds, and are asked if the card is found in your hand or not?
What are the steps you perform to get to the answer?
1- You look at each individual card in your hand and compare it against the searched card (queen of diamonds).
2- If the card is queen of diamonds, you can be certain that it is available in your hand. You don’t search further. Break out of the loop, and return with the answer.
3- If you have reached the last card and it’s still not the queen of diamonds, you are certain that the card does not exist in your hand. So, you return the answer saying that you don’t have the card.

Note that step 3 is only valid if you are checking the last card in your hand. If you were at card 2 and it wasn’t queen of diamonds, you couldn’t conclude that queen of diamonds does not exist in you hand, because there are still other possible cards left unchecked.
That’s the reason why in the code you are checking i === contacts.length -1. In plain English, this expression means that you are checking the last card (contact name or anything else for that matter). And also implies that the search card/contact was not found until this point. So, if this last card/contact is not the one you seek, the searched card/contact does not exist in your hand/contact book or whatever collection.

Now, I’ve gone through this to make sure you understand the logic. But, the code is not written very readable.
You can achieve the same result with more readable code by writing something like this:

// This is pseudo code
searchedCard = "queens of diamonds"

for card in cards:
    if card == searchedCard:
        return  "card found"

return "card not found"

You see, we don’t need to check at every iteration of the loop whether it’s the last card. We just check them all. If we find the card we do our business and return.
If the loop ended naturally (without us returning/breaking out of it), we are sure that the card was not found.

Hope that helps.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.