My solution is not working and I don't know why [Lookup Profile]

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"]

    }

];
My solution
function lookUpProfile(name, prop) {

    for (const property in contacts) {

        if (contacts[property].firstName === name && contacts[property].hasOwnProperty(prop)) {

        return contacts[property][prop];

        } else {

        return `No such property`;

        }

    }

}

For some reason, it’s always returning “No such property” even if I put arguments that pass the test. If I remove the return in the else clause it works as intended.

I tried to create a variable to assign the results so I could return it outside the loop but it didn’t work.

I appreciate any help!

  1. You are returning inside of your for loop. The function immediately stops as soon as a return statement is encountered.

  2. I would stop and think about the logic here.

Your else clause will always run if the condition in the if statement is not true. There are two different things that could make your if condition false.

1 Like

That’s the thing though, this loop/function doesn’t stop after the return statement, it stopped the current evaluation and went to the next, then it kept evaluating and re-assigning the returned value. It took me almost 5 hours but I was able to solve it with this solution:

Final solution
function lookUpProfile(name, prop) {

    let result;

    for (const property in contacts) {

        if (contacts[property].firstName !== name) {

            result = "No such contact";

        } else if (!contacts[property].hasOwnProperty(prop)) {

            result = "No such property";

            break;

        } else if (contacts[property].firstName === name) {

            result = contacts[property][prop];

            break;

        }

    }

    return result;

}

Not as clean as fCC’s solution and I was only able to do it because I knew of the break keyword, but I’ll take it. In any case, thanks for the help.

Good job getting your code to pass.

If you put a return statement, the code will halt immediately. It must. That’s what return means. I suspect that your logic with the previous version of your code with return statements from returning as you expected.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.