Profile Lookup: Why must I set return "No such contact" outside the loop

Tell us what’s happening:

//Why can't this work
//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+=1){
        if(contacts[i].firstName === name){
            if(contacts[i].hasOwnProperty(prop)){
                return contacts[i].prop;
            }else{
                return "No such property";
            }
        }else{
            return "No such contact";
        }
    }
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");

Because you’re checking the entire array for that particular name. In your scenario, you’ll just return "No such contact" on every iteration when an item being iterated does not agree with your rules. So calling lookUpProfile("Akira", "likes"); will return "No such contact" three times, when it doesn’t have to, since Akira is in a database. If you called it with a name that doesn’t exist, you would iterate through every item, check it and once the loop is finished, you’ll be left with the only option - to declare that it doesn’t exist, because it couldn’t be found in a loop. You have to wait until every item in your array gets iterated, and only then return this desired output. :slight_smile: Sorry for such a verbose answer, hope you understand it better.

This is not correct. It will return it exactly once, before the loop has ended. You’re otherwise correct about the reason for the placement of the return statement: the reason you need to return after the loop has completed is because you need to examine all the elements of the data structure before you can determine that the condition isn’t satisfied.

1 Like

Thank you for pointing that out, that was a mistake.