Help for Test Skill: Loops 2

Hi, can anyone tell me why my code doesnt work when using a ‘for’ loop or a ‘while’ loop? Really confused with these loops.

https://codepen.io/vddroid/pen/wvKwddP

Hi @vddroid!

Looking at your code, you had everything right in this example, except for one thing. Once the correct name is found, and the name and number are then printed to the paragraph, you then need to break out of the loop, otherwise it just continues looping through all the other array items, and eventually prints the “No name found” message to the paragraph because it gets to the end of the array.

So to do this, you would add the break statement like so:

if (phonebook[i].name === name) {
  para.textContent = `${phonebook[i].name}'s number is ${phonebook[i].number}`;
  break;
}

Also, you probably don’t need else if here. You could simply the if statment block to

if (phonebook[i].name === name) {
  para.textContent = `${phonebook[i].name}'s number is ${phonebook[i].number}`;
  break;
} else {
  para.textContent = "No name found.";
}
1 Like

Thank you, forgot about the break;

Hi, Chris & vddroid.
I’ve followed the course and so far I haven’t seen this kind of array with fields anywhere, where are they explained?
Thanks.

Hi @opuskill! By “array with fields”, do you mean things like phonebook[i].name?

This is basically just shorthand for accessing an array element that contains a JS object. So for example:

let phonebook = [
      { name : 'Chris', number : '1549' },
      { name : 'Li Kang', number : '9634' },
      { name : 'Anne', number : '9065' },
      { name : 'Francesca', number : '3001' },
      { name : 'Mustafa', number : '6888' },
      { name : 'Tina', number : '4312' },
      { name : 'Bert', number : '7780' },
      { name : 'Jada', number : '2282' },
    ]

phonebook[0] would be equal to { name : 'Chris', number : '1549' }.

To return “Chris”, we could do phonebook[0].name — accessing the name property of the object stored at array index 0.

1 Like

Hi, Chris.
Yes, that’s what I meant. This array is a “normal” array? Are they built the same way of others?
Thanks for the answer and excuse me for insist. Regards.

@opuskill Yes — this is a normal array; it is just that the value at each array index is an object.

Always happy to answer questions!

I can propose my solution:

while (i < phonebook.length) {

  let myObject = phonebook[i];

  let myArray = Object.values(myObject);

  if (myArray[0] === name) {

    para.textContent = `${myArray[0]}: ${myArray[1]}.`;

    break;

  }else{

    para.textContent = `Sorry, we dont found the name.`;

  }

  i++;

}

Hello teacher I’m new here, pls help me with my code…
First I tried for loop, it works well, then I tried while loop, I’m not sure how it supposed to work :grin: :grin: :grin:

here is the link:
[https://codepen.io/kd0149/pen/LYpJBoY]

Thanks a lot!

@ThreeTwoBeats hi there!

I am a little bit confused — this code seems to work fine, so what is the question here? :wink:

The only bit of feedback I have is that it seems strange that you are generating all the DOM elements with JS, when you could just use HTML and save yourself a lot of code. But I guess you are experimenting, and that’s fine for now.

@chrisdavidmills Hi, thanks for replying! Well, the name can only be searched starts from the front to the back, if I want to search by the opposite way it doesn’t work anymore.

The reason I generating all the DOM elements with JS is because I thought I can only adding codes under the javascript section below the comments line. :sweat_smile:

Hello, i need help here too:
in the console it works fine, Mustafa shows up, but its not added to para.textContent from the the loop to see on the website then!?

for(i = 0; i <= phonebook.length; i++){
  if(phonebook[i].name === name){
    console.log(phonebook[i]);
    console.log(phonebook[i].name + ': ' + phonebook[i].number);
    para.textContent = phonebook[i].name + ': ' + phonebook[i].number;
  } else {
    para.textContent = 'Contact not found.';
    };
    
};


hello!! i found the solution: i added a ‘break;’ before the else statement! now it shows Mustafa and the Number on the site, phew! test done!!!
but why is the break; so important here? i thought the loop iterates through the whole phonebook, if it finds a match it adds it to the site, then it goes further through, the book and the else statement is only there to test if something goes wrong, not for the user rather than me as programmer!? why do we need the break here?
and one more thing if i want to test now what happens if i delete Mustafa in the phonebook, i need to add a break in the else statement too, to show contact not found. is my code the wrong approach to this?

    for(i = 0; i <= phonebook.length; i++){
      if(phonebook[i].name === name){
        console.log(phonebook[i]);
        console.log(phonebook[i].name + ': ' + phonebook[i].number);
        para.textContent = phonebook[i].name + ': ' + phonebook[i].number;
        break;
      } else {
        para.textContent = 'Contact not found.';
        break;
        };
      };

Hi, thanks for replying! Well, the name can only be searched starts from the front to the back, if I want to search by the opposite way it doesn’t work anymore.

I think that’s OK for this demo.

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.

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

1 Like

oh! thank you very much @chrisdavidmills!! got it now

@ppirx you are most welcome.

I even realized that i could write …, i < phonebook.length… instead of i <= phonebook.length to avoid the iteration over to 8 positions which is wrong…as you mentioned. :wink:

ha, that’s even better :wink:

ahh I also forgot the “break”. thanks for this!