Basic Javascript, Lookup Profile Challenge - question about position of final return statement

Spoiler alert! This question is about the last main challenge in the Basic Javascript course. If you’re working on the solution and you want to work it out for yourself, leave this page now!

I thought I’d solved this problem but for every combination of parameters I passed to the function I got “No such contact”:

console.log(lookUpProfile("Sherlock", "lastName")) // No such contact (Should be: Holmes)
console.log(lookUpProfile("Sherlock", "likes")) // No such contact (Should be: "Intriguing Cases", "Violin")
console.log(lookUpProfile("Sherlock", "hobbies")) // No such contact (Should be: No such property)
console.log(lookUpProfile("Watson", "likes")) // No such contact (true)

So I went to the ‘hints’ page. Hint 1 - I’d done that ok. Hint 2 - I done that one as well.

So I looked at the final hint: put the final return statement (“No such contact”) outside of the for loop as a catch-all for when the conditions inside the loop weren’t met.

And, of course, it worked.

But I’m still scratching my head about why my solution doesn’t work.

My (wrong) solution:

function lookUpProfile(name, prop){

    for(var i = 0; i < contacts.length; i++){
        
        if(contacts[i]["firstName"] === name){            

            if(contacts[i].hasOwnProperty(prop)){
                return contacts[i][prop]
            } else  {
                return "No such property"
            } 
            
        } else {
            // Incorrect position - "No such contact" is returned for everything
            return "No such contact"
        }
    }
    // Correct position
   // return "No such contact"
}

I see the logic of my solution as:

if: firstname exists continue on to:
----- if: props exist then:
---------- return the value of that property
----- else:
---------- report that property as non-existent
else: (as firstname has not been found)
----- report firstname as non-existent

Could anyone explain the flaw in my logic? :slight_smile:

  1. Remember that returning takes you out of the loop.

  2. The first person is Akira, let’s look at what happens when we look for Harry.

var contacts = [
    {
        "firstName": "Akira",
        "lastName": "Laine",
        "number": "0543236543",
        "likes": ["Pizza", "Coding", "Brownie Points"]
    },
    {
        "firstName": "Harry",
        "lastName": "Potter",
        "number": "0994372684",
        "likes": ["Hogwarts", "Magic", "Hagrid"]
    },
}

// On the first loop iteration contacts[i]["firstName"] will be Akira
// we are looking for Harry so the condition in the if statement is false
// so we hit the else and return out of the for loop
// which means we never finish iterating the array and never find Harry

if(contacts[i]["firstName"] === name) {
  ...do something
} else {
  return something
}


lookUpProfile("Harry", "likes")

Thanks - I understand!