Skip to content
Advertisement

Basic Profile Lookup always returning no contact found

So I’ve recently begun learning Javascript using the tutorials on freecodecamp and there’s this challenge I’ve been stuck on for a few hours now.

The function always returns ‘No contact found’ and I don’t understand why. If someone were to explain it to me and correct my code, I’d be grateful.

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) {

  for (var i=0; contacts.length>i; i++) {

    if (contacts[i][firstName]==firstName) {
      if (contacts.i.prop.hasOwnProperty()===true) {
        return contacts.i.prop;
      } else { return "No such property";
     }
    } 
      return "No such contact"; }
}

lookUpProfile("Akira", "lastName");

Advertisement

Answer

Try this

Explanation

  1. Typo error change like this contacts[i]['firstName'] instead of contacts[i][firstName].you are missing to match the keyname of obj.for your way its calling like

    contacts[i][Akira] == false statement so only it always go else statement

  2. Do the object key call method with obj[key] instead of obj.key .Beacuse all are varible not with direct name of the key

  3. second one hasownproperty(varible) .you are not mention which word to check with that object

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) {

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

console.log(lookUpProfile("Akira", "lastName"));
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement