Js Lookup challenge

please help , my code wont iterate through the whole contacts list


function lookUpProfile(name, prop){
  for (var i = 0; i < contacts.length; i++) {
      if(contacts[i]["firstName"] === name && contacts[i].hasOwnProperty(prop)) {
          return contacts[i][prop];
      }else if(contacts[i]["firstName"] !== name) {
          return "No such contact";
      }else if(contacts[i].hasOwnProperty(prop) === false) {
          return "No such property"
      }
  }
}

lookUpProfile("Akira", "lastName");

And there’s a precise reason for that, you are actually telling it to not do it.
Remember that a return statement inside a loop stop the execution.

Without giving away too much, try thinking why your function is exiting :slight_smile:

1 Like

@Marmiz i love your response , i think i can correct my error now :sweat_smile:

ok , i have tried creating a variable , but still no success … i dont know where im getting it wrong

function lookUpProfile(name, prop){
  var answer = "";
  for (var i = 0; i < contacts.length; i++) {
    
      if(contacts[i]["firstName"] === name && contacts[i].hasOwnProperty(prop)) {
          answer = contacts[i][prop];
      }else if(contacts[i]["firstName"] !== name) {
          answer = "No such contact";
      }else if(contacts[i].hasOwnProperty(prop) === false) {
        answer = "No such property";
      }
      
  }
  return answer;
}

No worries, this is a common error that usually takes practice to “read”.

In pseudo-code this is what your code is instructed to do, I’m talking about the first version: the return one

Loop on every element
  if element x firstName is name and element x has property
      Stop and return element x property
  if element x firstName is not name
     Stop and return "No such .."
  if element x don't have prop
    Stop and return "No such.."

Do you see the error?
Or in other word, how can I stop at the first element and tells “We don’t have it” if we haven’t checked them all first?

1 Like

Thanks @Marmiz

function lookUpProfile(name, prop){
  
  for (var i = 0; i < contacts.length; i++) {

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

  }
    
  return "No such contact";
}
1 Like

Good job @KnowledgeWorker!
Good luck and happy coding :sparkles:

1 Like