Stuck on Profile Lookup Challenge

Hi,
I hope everyone’s doing well. I’m stuck on this little challenge called Profile Lookup from the Basic Javascript section.

What I’ve done so far is:

function lookUpProfile(name, prop){
    for(var i in contacts) {
        if(contacts[i].firstName == name) {
            if(contacts[i].hasOwnProperty(prop)) {
                return contacts[i][prop];
            } else {
                return "No such property";
            }
        } 
        return "No such contact";
    }
}

In this, when I remove the return statement that’s in the end, the code works fine (ofcourse the cases where the last return statement required, fail).
And when that last return statement is there, the code above it, fails.

Can anyone help me understand what’s happening? I spent hours checking if I’m accessing the objects wrong, missing anything, etc. But just couldn’t figure it out.

Thanks!

Update: I put the last return statement out of the for loop and it worked :sweat_smile:. But I feel like it should have also worked when it’s inside the for loop. I still need answers as to why it doesn’t work inside the for loop. Because at any case, one of the three return statement must execute.

Because having the return "No such contact" command IN the for loop means it will return “No such contact” if your very first contact doesn’t match the name argument - the loop hits that return statement and ends the function.

1 Like

the issue is that once a return statement is met, the function stops and return a value.

So, if at first iteration contacts[i].firstName == name is false, the function doesn’t check the others because it finds the return "No such contact" line, returns that and stop

2 Likes