Profile LookUp -- alternate solution check

I saw the answer for this exercise and it makes sense. Can someone explain to me why my code here doesn’t work and/or what I can do to make it work still?

for(var i = 0; i < contacts.length; i++){
        if(contacts[i].hasOwnProperty("firstName") == true){
            return contacts[i].prop;
        } else {
            return "No such contact";
        }
    }

There are a couple of problems.

First, you need to think about your logic. You need to check if the first name matches and then if it does, then you check if that passed in property exists. It it does exist, then you either return that property and if not, you say that that property doesn’t exist.

The other problem is that when you refer to that prop:

contacts[i].prop

That is how you would refer to it if there was a prop called prop. But there isn’t, prop is a variable. When you use a variable to refer to a property, it has to be objectName[propertyName].

The other problem is that you are only checking the contact - that if statement is only going return one or the other on the first time it’s hit. But that will be fixed once you fix your logic. I think this problem needs two if statements (or an if and a ternary).

The last problem is that you haven’t accounted for what happens if the property doesn’t exist.

2 Likes

thanks for taking the time to respond!