Profile Lookup - help

Tell us what’s happening:
What am I doing wrong here?

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(firstName, prop){
// Only change code below this line
for(var i = 0; i < contacts.length; i++){
  if(contacts[i].firstName === firstName){
    if(contacts[i].hasOwnProperty(prop)){
      return contacts[i][prop];
    } else {
      return "No such property";
    }
  } else {
    return "No such contact";
  }
}
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Kristian", "likes");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0.

Link to the challenge:
https://www.freecodecamp.org/challenges/profile-lookup

Ok I passed but only by experimenting What I did not understand is that why is my “no such contact” outside my if statement that checks if the name matches?

function lookUpProfile(firstName, prop){
  // Only change code below this line
  for(var i = 0; i < contacts.length; i++){
    if(contacts[i].firstName === firstName){
      if(contacts[i].hasOwnProperty(prop)){ 
        return contacts[i][prop];
      } else {
        return "No such property";
      } 
    }   
  } 
  return "No such contact";
  // Only change code above this line
}

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

It is not only outside the first if statement, it is also outside the for loop. It has to be outside the for loop, because only once you have iterated through all the contacts can you be certain the firstName does not match. Why? Because if it would have matched, the inner if/else statement would have returned either the property or “No such property” and the function would have exited.

1 Like

Yes, that makes so much sense. Thanks for taking the time out to explain.