Practice Exercises - Objects & Array Objects #40

Hi, I have come with a solution but the condition “else” does not work, although I have no idea why. Can you help please?

Task:
40. Simple phone book.

In this assignment, we will create a simple telephone directory, where the user can search by name to retrieve the telephone number.

  1. Create an object.
  2. Fill the object with the following relations. The name should be key and the phone number should be the value:
  3. Have the user enter a name, then print the phone number that belongs to that name. If the user enters a name that does not exist in the object, give an error message stating that we have not saved this number.

My solution:

<input type="text" id="name" placeholder="Enter name">
<button type="button" id="button">Find number</button>
<p id="phone"></p>

<script>

  var phonebook = {Carlos:22334455,
                  Gabba:95959595,
                  Ivo:97959795,
                  Fabrice:12345678};

  $("#button").click(function(){
    var enteredName = $("#name").val();
    $.each(phonebook, function(index, value){
      if(index == enteredName) {
        var phoneNumber = value;
        $("#phone").text("Phone number is: "+phoneNumber);
      }
      else {
        $("#phone").text("Sorry, name was not found in database.");
      }
    });
  });

</script>

It’s really tricky. Because if I delete the line with condition “else”:

  else {
    $("#phone").text("Sorry, name was not found in database.");
  }

then it works normally, like this: I enter a name from the phonebook (for example “Carlos”) and it gives me “Phone number is: 22334455”. Which is correct.

However if name was not found in object then I need to write “Sorry, name was not found in database.”. So I added simple “else” condition described above. But it gives me “Sorry, name was not found in database.” in all situation no matter the name entered, even though the name is in the object.

I can’t understand that. Can you help me please? I have also other working solution, but I need to figure out this one. Thanks!

The issue with your code is that you are doing the result writing in the loop itself. Thus, even if you get the match of the number, the loop keeps doing the looping and eventually the last result will show no phone number found.

Your code ought to be –

  var phonebook = {
        Carlos: 22334455,
        Gabba: 95959595,
        Ivo: 97959795,
        Fabrice: 12345678,
      };

      $("#button").click(function () {
        var enteredName = $("#name").val();
        var FounMatch = false;
        var phoneNumber = 0;
        $.each(phonebook, function (index, value) {
          if (index == enteredName) {
            phoneNumber = value;
            FounMatch = true;
          }
        });

        if (FounMatch) {
          $("#phone").text("Phone number is: " + phoneNumber);
        } else {
          $("#phone").text("Sorry, name was not found in database.");
        }
      });

Hope this helps.

1 Like

It helped, thanks a lot. Somehow I thought that when loop finds the value, it stops looping, lol. Now I can understand it is wrong.

However now I might see a better solution which should be more friendly. Because if loop continues until the end, we can just end the loop early when it finds the value. So I googled how to stop the loop and this solution looks better according to my opinion, don’t you think?

      var phonebook = {
        carlos:22334455,
        gabba:95959595,
        ivo:97959795,
        fabrice:12345678,
        monika:999666999,
      };

      $("#button").click(function(){
        var enteredName = $("#name").val().toLowerCase();
        $.each(phonebook, function(index, value){
        var phoneNumber = 0;
          if(index == enteredName) {
            phoneNumber = value;
            $("#phone").text("Phone number is: "+phoneNumber);
            return false;
          }
          else {
            $("#phone").text("Sorry, name was not found in database.");
          }
        });
      });

Yeap. This is a more efficient way of writing this piece of code. Way to go ! :smile:

Hello All,

I managed to figure out the first two exercises by myself, however, I am a little stuck on the last one, I have looked at the cheat sheet, which I hate doing, but I am still a little stuck, can anyone point to what I’m not getting here?

const flagObject = {"norway": ["red", "white", "blue"], "sweden": ["blue", "yellow"], "denmark": ["red", "white"], "finland": ["white", "blue"], "japan": ["red", "white"], "gabon": ["green", "yellow", "blue"], "United Kingdom": ["red", "blue", "white"], "chile": ["blue", "white", "red"]}

function colour () {

let country =prompt("Enter country name");

country = country.toLowerCase();

if (country in flagObject) {

console.log(flagObject[country]);

}

else {
console.log("The country", + " " country, + " " + "is not here");
}
}

colour();

Please remove the commas from your console.log, It will work then.

So I removed the quotes, and followed the guide, but I was/still getting an error,

let flagObject = {“norway”: [“red”, “white”, “blue”], “sweden”: [“blue”, “yellow”], “denmark”: [“red”, “white”], “finland”: [“white”, “blue”], “japan”: [“red”, “white”], “gabon”: [“green”, “yellow”, “blue”], “United Kingdom”: [“red”, “blue”, “white”], “chile”: [“blue”, “white”, “red”]
}
console.log(flagObject);
flagObject[“Spain”] = [“red”, “yellow”];

function locatecolour () {
let country = prompt(“Enter country name”);

country = country.toLowercase && country.toUppercase();

if (country in flagObject) {
console.log(flagObject[country]);
}
else {
console.log(“this country”, country, “is not in the database”);
}
}
locatecolour();

So I added the && country.toUppercase, as I was getting an error still,
it kind of works, but in the console, the country that I enter, even if it is, or isn’t in the list comes up with,

this country undefined is not in the database

Any ideas anyone?

Hi @Andre_Mark,

I had asked you to remove the commas, not the quotes. Please refer to my answer above.

That will solve the issue.

Thanks