Profile lookup(task 216)[SPOILERS]

so i was stuck on this task for hours(lol) but this was my resulting code and im looking for critique of it for ideas on how i could have made it better, this is what i came up with eventually

for(i=0;i<contacts.length;i++){
if(contacts[i].firstName==firstName){
if(contacts[i].hasOwnProperty(prop)){
value=contacts[i][prop];
break;
}else{
value=“No property exists”;
break;
}
}else{
value=“No name exists”;

}

}

Pretty similar to what I did when I tried that challenge a few months ago. I apparently used a Boolean value for a variable I called “noname”, that would be set to false if a name was found. I seem to have made it just return the value if it had a firstName and the desired property, which stops the function similar to your use of break, but doesnt use a variable for “value”.

  for(i=0;i<contacts.length;i++){
   if(contacts[i].firstName==firstName){
     noname=false;
     if(contacts[i].hasOwnProperty(prop)){
       return contacts[i][prop];
      }
    }
  }
  if(noname){
    return "No such contact";
  }
  return "No such property";

I should mention I’m a relative beginner myself, so I cant vouch for the quality of my solution, but I dont see anything bad about either of our ways of solving it.

Btw to show a code snippet you put 3 backticks (`) before the code (you can put them after the code to close it too) just so it formats in an easier to process way.

good luck!

Your code is relatively hard to read at first glance, plus writing lots of if else statement is generally not considered as a great idea because it may lead you to make more mistakes.
(the more you write the more chance you have to make mistakes)

In conditions like this is often considered a good practice to use “early returns”.
There’s a guide on the forum explaining it that I’ll link at the end of the post.

In short the same logic you’ve used can simply be skimmed down to (in pseudo-code) as:

function lookupProfile() {
loop {
    if contact.firstname === firstname {
        if contact hasOwnProp {
            return contact[prop]
       }
     // here we can execute a return assuming that the prop is not here
    // since the previous statement has not been executed
    return no property 
    }
}
// same here, we can return no contact because if we reached this far means
// the contact is not in the list
return no contact
}

Hope makes sense :slight_smile:

what i learned from this is it sometimes may be easier to check a value to see if its not true rather then just always true