7/8 search for a friend.. can anyone see why this isn't working


#1

Here's my code

var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "111-5555",
address: ['Scottsdale', 'AZ', '85260']
},
friends.steve = {
firstName: "Steve",
lastName: "Jobs",
number: "555-5555",
address: ['Cupertino', 'CA', '95260']
}

var list = function(friends) {
for (var key in friends) {
console.log(key)

}

};

var search = function(name) {
for (var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
else {
return 'none'
}
}

};

list()
search("Steve")

I switched the format of my object to this one..
the error and log says...

"Oops, try again. It looks like your search function doesn't return contact information for Steve."
and
"{ firstName: 'Bill',
lastName: 'Gates',
number: '111-5555',
address: [ 'Scottsdale', 'AZ', '85260' ] }
"none""

I've searched the forum and can't see what is going wrong..
Thanks


#2

The problem is your else statement. Think about it logically when the program runs through the loops. The first entry in your friends object is Bill.

Your If-Statement is going to return false and drop down to the else you coded in. The return causes the function to stop running, preventing it from finding the "Steve" entry in your friends object, and instead just returning the string 'none' as a result.

When creating If-Statements, you don't always need to include an else statement, this would be one of those times were it's going to cause issues with how your code functions, especially with that return statement.

Javascript Return statement gives some info on how the return works.


#3

Wonderful explanation! Thanks a million.. That makes great sense.
It works now.