7/8 Search for a friend


#1

//This is my code

var friends = {
Bill: {
firstName: 'Bill',
lastName: 'Prady',
number: '044 9627015',
address: ['F 32/2', 'Neulamaki', 'Kuopio', 'Finland']
},
Steve: {
firstName: 'Steve',
lastName: 'Steven',
number: '044 9627020',
address: ['F 31/1', 'Puijonlaakso', 'Helsinki', 'Finland']
}
};
var list = function() {
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 "We can not find anything by that name";
} } }

The result is that Oops, try again. It looks like your search function doesn't return contact information for Steve. If I delete the else statement, the result is right. I do not understand the reason when I add the else statement, it just prints Bill information only.


#2

That's because you wrote

Calling return in a function will terminate that function. and yield that value you are returning(in this case 'We can not find anything by that name')

When the loop starts and it finds that the first key's firstName is not what you are searching for then it will move in to the else block and terminate the function