Basic JavaScript: Profile Lookup assistance

Basic JavaScript: Profile Lookup assistance
0.0 0

#1

I’m having trouble figuring out why this code is not passing all tests. It’s only failing on “Bob”, “potato”. I assume it’s because it’s leaving the for loop once it hits this iteration, but I’m not sure how to get it to iterate again.

“Kristian”, “lastName” should return “Vos” - passed
“Sherlock”, “likes” should return [“Intriguing Cases”, “Violin”] - passed
“Harry”,“likes” should return an array - passed
“Bob”, “number” should return “No such contact” - passed
“Bob”, “potato” should return “No such contact” - failed
“Akira”, “address” should return “No such property” - passed

Any help would be much appreciated! The relevant code is below:

function lookUpProfile(name, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++) {

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

return "No such contact";
// Only change code above this line
}

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

This will return if hasOwnProperty is false, regardless of whether the first name matches.


#3

The problem with your solution is the line:

return "No such contact";

is not being executed, because your else if statement evaluates to true for this particular test case.


#4

So should my else if be testing for the first name as opposed to a property?


#5

Right now when the “Bob”, “potato” test runs, this is what happens:

  • The loop starts with the first item in contacts
  • The first if condition fails.
  • contacts[0] does not have a property potato, so the function returns "No such property".
  • The end.

#6

Got it by adding

else if(!(contacts[i].hasOwnProperty(prop)) && (contacts[i].firstName === name))

Thanks for the help!