Profile Lookup - logic seems ok but code doesn't execute according to (my) logic :(

Hello mates, I can’t understand why my solution will result in ‘no such a contact’.

//Setup
var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
    {
        "firstName": "Sherlock",
        "lastName": "Holmes",
        "number": "0487345643",
        "likes": ["Intriguing Cases", "Violin"]
    },
    {
        "firstName": "Kristian",
        "lastName": "Vos",
        "number": "unknown",
        "likes": ["JavaScript", "Gaming", "Foxes"]
    }
];
function lookUpProfile(name, prop){
// Only change code below this line
for (let i = 0; i < contacts.length; i++){
    var contact = contacts[i]; //contact is now an object
    if ( contact.firstName === name ){
        if ( contact.hasOwnProperty(prop) ){
            return contact[prop];
        } else {
            return 'No such property';
        }
    } else {
        return 'No such contact';
    }
}
// Only change code above this line
}

I Looked at the solution, and it seems that the last return statement (’’'return 'No such a contact```) must be placed out of the for loop. But why? Should not a return statement stop and exit the function (and so the for loop too?)

For example, in the first if, if name is not equal to the firstName, then it should execute the outer else branch which returns ‘No such contact’. That what happened even when the firstName is equal to name…but why? Any help? thank you in advance

Can you post a link to the exercise?

The problem starts from your IF to Else.

And more specifically when the compiler meets return and returns something, the code stops there. (that’s what return does).

You can try and console.log(contact) and you will see that only one firstName has been printed to the screen, which means that the for loop run only time and stopped.

Hint: You should better combine the first two IFs into 1 and try to find a way to not stop the for loop from running and at the same time return all necessary strings.

This is the link:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup/

Thanks for your reply. I understood where it does not work.

Basically the for loop needs to run until the end (or until it finds a match) otherwise at the first non-match (even though a match would exist in one of the following objects in the array) the function (and the loop) will exit due to the return statement.

Thanks for you help

Yeah, exactly.

Don’t hesitate to ask more questions.

I’ll be glad to help.

Much appreciated. Thanks a lot!

You’re welcome.

Good Luck & Happy Coding.