I've been tackling a project that involves a contact list called contacts
, which is an array
filled with objects
.
The issue I'm facing is that my function searchPerson
consistently returns "No such person found!" even when the searched-for individual exists. Surprisingly, if I remove the condition and rerun the function, it successfully finds the desired entry.
I'm puzzled as to why, with the condition in place, it repeatedly shows "no such person found!" while the person does indeed exist in the contact list! Could someone provide insights into why this unexpected behavior is occurring?
Below is the snippet of the code:
var bob = {
firstName: "Bob",
lastName: "Jones",
phoneNumber: "(650) 777-7777",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f4f9f4b8fcf9f8f3e5d6f3eef7fbe6faf3b8f5f9fb">[email protected]</a>"
};
var mary = {
firstName: "Mary",
lastName: "Johnson",
phoneNumber: "(650) 888-8888",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f79a96858ed99d989f99849899b7928f969a879b92d994989a">[email protected]</a>"
};
//Here we populate our array.
var contacts = [bob, mary];
function printPerson(person) {
console.log(person.firstName + " " + person.lastName);
}
function searchPerson (lastName) {
var contactsLength = contacts.length;
for(var i = 0; i < contactsLength; i++){
//set a condition that we only retrieve the last name if it already exists in our contact list
if(lastName !== contacts[i].lastName){
return console.log("No such person found!");
} else {
printPerson(contacts[i]);
}
}
}