Profile Lookup - what is wrong with my code

Tell us what’s happening:

What is wrong with my code?

Your code so far


// 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 (var i = 0; i < contacts.length; i++){
if (name == contacts[i]["firstName"]){
if (contacts[i].hasOwnProperty(prop)){
    return contacts[i][prop]
}
return "No such property"
}
return "No such contact"
}
// Only change code above this line
}

lookUpProfile("Akira", "likes");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.

Challenge: Profile Lookup

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

inside your loop at least one return statement will always execute, it means that the loop will stop at i = 0, and check only the first element in the array, never the others

you can use the tool pythontutor (find it on google!) to see how your code execute

function lookUpProfile(name, prop){
// Only change code below this line
for (var x = 0; x < contacts.length; x++) {
    if (name == contacts[x].firstName) {
        if (contacts[x].hasOwnProperty(prop)) {
            return contacts[x][prop];
        }
            return "No such property";
        }
    }
    return "No such contact"



// Only change code above this line
}

I don’t understand why last return statement need to be there

Why it cant be like this:

function lookUpProfile(name, prop){
// Only change code below this line
for (var x = 0; x < contacts.length; x++) {
    if (name == contacts[x].firstName) {
        if (contacts[x].hasOwnProperty(prop)) {
            return contacts[x][prop];
        }
            return "No such property";
        }
        return "No such contact"
    }
    // Only change code above this line
}

Ok I think I get it. If the function looked like this:

function lookUpProfile(name, prop){
// Only change code below this line
for (var x = 0; x < contacts.length; x++) {
    if (name == contacts[x].firstName) {
        if (contacts[x].hasOwnProperty(prop)) {
            return contacts[x][prop];
        }
            return "No such property";
        }
        return "No such contact"
    }
    // Only change code above this line
}

We won’t let function to cycle through all of contacts elements.

Glad you solved it! Happy coding!