Profile Lookup - Just one main difference to my solution, but not working

Tell us what’s happening:

Hello all,

I managed to somewhat piece the code together similarly to the solution, except for a slight difference which won’t work. I have the

 else {
  return "No such contact";
}

inside of the for loop rather than outside (solution is outside). I’m having a hard time understanding why mine would not work. Can someone shed light on this?

Thanks!
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) {
  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 {**
**       return "No such contact";**
    }
  }
}

// Change these values to test your function
var k = lookUpProfile("Kristian", "lastName");
console.log(k);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36.

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

let’s say that the function call is lookUpProfile("Kristian", "likes")
when i is 0, contacts[i].firstName is Akira, and name is Kristian

if (contacts[i].firstName === name) {
   ...
} else {
   return "No such contact"
}

Here, "Akira" === "Kristian" is false, the else statement is executed, the function returns the string and stops there
the other items in the array are not checked

As soon as a return statement is executed, the function exits. This means if you leave the else statement inside the for loop, it would only ever make it one iteration before return something and then exiting. You only want to return “No such contact” once you have been through the entire contacts array and not already returned a property value or “No such property”. The only way to do that is to wait until the for loop is complete.

you’re right, thanks!