Search function not working


#1

Hi everyone!

var search = function(name) {
for (var firstName in friends) {
if(friends[firstName].firstName === name) {
console.log(friends[firstName]);
return friends[firstName];
}
else {
return "Name could not be found";
}
}
}
search("Steve");

So I got stucked at the search function of my contact list. I created an object called friends that contains three other objects friends.name, and all three have a value called firstName = 'Name'. So that's that, and the list function works fine. But, when I try to look for a specific firstName in the object friends I don't get the expected result, but "Oops, try again. It looks like your search function doesn't return contact information for Steve.", and the console log gets me the else statement, "Name could not be found".

Is my understanding that if var friends = new Object(); is in global scope, all its content (so all the objects inside) are in global scope too, so search function should be able to look through the values inside?

I will really appreciate your help.

`


#2

a function ends the moment a return keyword is reached

for your function, this means, either the first entry is a match and the contact information is reached or Name could be found is returned. Either way, your function ends after the first contact person, the second, third person (and so on) are never reached

you only want to return not found after the loop


#3

Thank you so much, I would never have get there all by myself, it works perfectly now.
I am still struggling with the internal logic of loops, I really appreciate your explanation, I think it will help me avoid this kind of mistake in the future. Again, thanks!


#4