I was practicing some JavaScript on Codeacademy few minutes ago and I found something confusing. Here is the code:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "(408) 555-5555",
address: ['1 Infinite Loop','Cupertino','CA','95014']
};
var list = function(obj) {
for(var prop in obj) {
console.log(prop);
}
};
var search = function(name) {
for(var prop in friends) {
if(friends[prop].firstName === name) {
console.log(friends[prop]);
return friends[prop];
}
else {
return "contact not found";
}
}
};
list(friends);
search("Steve");
The problem is that when I pass the string "Steve" as an arg in the search function, it returns the condition "Contact not found" while when I pass the string "Bill" as an arg in the same search function, it displays the contact information.
How is that possible? What am I doing wrong?
In your code, in the first iteration of the loop, the prop
value is something else apart from Steve
. So, the if
condition fails, reaches the else
part and returns contact not found
immediately.
But, you should return not found
message only when none of the objects's firstName
matches, like this
function search(name) {
for (var prop in friends) {
if (friends[prop].firstName === name) {
return friends[prop];
}
}
return "contact not found";
};
else {
return "contact not found";
}
You're returning not found as soon as you find a contact that doesn't match.
You shouldn't give up until you run out of items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With