Profile lookup - code works (and not really) and I don't know why...

Can someone explain to me why following code is wrong ?

  • “Kristian”, “lastName” should return “Vos”
  • “Sherlock”, “likes” should return [“Intriguing Cases”, “Violin”]
  • “Harry”,“likes” should return an array
    Those are the points that are not fulfilled for this task, so it looks like first “if” does something wrong… BUT! If i delete last else if and I put it’s return after the whole “for”, it works. I don’t really get that :confused:
function lookUpProfile(name, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {
    if (name == contacts[i].firstName && contacts[i].hasOwnProperty(prop)) {
        return contacts[i][prop];
    } else if (name == contacts[i].firstName && !contacts[i].hasOwnProperty(prop)) {
        return "No such property";
    } else if (name !== contacts[i].firstName) {
        return "No such contact";
// Only change code above this line

I asked this question in a Topic about Profile Lookup but I think it’s a bit different matter here so I decided to start a new one. Is that ok? Should I delete it from there so that it’s not duplicated?

Many thanks for your interest :blush:

Your code can’t return in the middle of searching.

Suppose you are looking for John and he is at the end of the contact. The first guy on the contact is Jim. Now, your lookup process sees Jim and decides John doesn’t exist, which is false. Do you see the problem?

Oh, so in this case I’m forcing the code to give me a return in the first run before it checks other contacts? And based on the first run, function tells me that this person doesn’t exist because it stops before going through the whole list?
So basically, here, I get proper result only if the (name, prop)

  • is giving a name of a person from contacts but with invalid, non existing prop, (“No such property”)
  • is giving name that is not in our contacts (“No such contact”)
  • is giving name of the 0th element / 1st contact and prop that it actually has ?

You have the first two understood, but I am not exactly sure what you are trying to state in the last bullet point, so it is hard to tell if you understand everything.

You only get a proper result, if the first contact actually meets the condition for the first two if branches.
For example, suppose John is the first one in the contact and he is the one you are looking for.

  • If he has the property, then you are fine.
  • If he doesn’t have the property, you are also fine.

Asserting “No such contact” is only possible once you’ve looked up the entire contact.

Yeah, after reading it I see how werd I wrote that one…
I meant that I also get proper result for e.g. (Harry, likes) if Harry is the first person in the contacts AND he has the property “likes”. So basically like gunhoo93 said in more understandable way:

I think I get it now but I’m still not sure if I could get to that by myself.