Profile lookup task of JavaScript portion (216)

Profile lookup task of JavaScript portion (216)
0.0 0

#1

My code is :

function lookUpProfile(firstName, prop){

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

I dont know what is the problem in my logic. any help would be appreciated. Thanks


#2

Your logic is flawed.

That’s how you have structured your code in pseudo-code:

loop over contacts
look at the first item
 1. is name and prop the same as one asked ? (yes) return the property
 2. is the name different the name? (yes) return no contact
 3. does the element do not have a property? (yes) return no property.

Now remember that function steps are executed in order.
So what happens if I ask you to look at name = Harry Potter, that in our list is second?

The program start and look at the first contact.
Execute point 1.
They don’t mach so we move to step 2.

Now is the name Harry Potter the same as Akira Laine?
No!
So return No such contact.

But we never even looked at the second contact to see if it was there.


Hope this example helps you in better understand the logic you should follow for this exercise :slight_smile:


#3

Thanks so much Marmiz. Got it. :slight_smile:
I changed my code to this and it worked:

function lookUpProfile(firstName, prop){

for(var i=0;i<4;i++)
{
if(contacts[i].firstName==firstName)
{
if(contacts[i].hasOwnProperty(prop))
{
return contacts[i][prop];
}
else
{
return “No such property”;
}
}
}
return “No such contact”;
}