Another JavaScript challenge on Free Code Camp!

Problem Statement

We have an array of objects representing different people in our contacts lists.

A lookUpProfile function that takes name and a property (prop) as arguments has been pre-written for you.

The function should check if name is an actual contact's firstName and the given property (prop) is a property of that contact.

If both are true, then return the "value" of that property.

If name does not correspond to any contacts then return "No such contact".

If prop does not correspond to any valid properties of a contact found to match name then return "No such property".

Final Solution


function lookUpProfile(name, prop){
  const contact = contacts.find((aContact) => aContact.firstName == name);
  if(!contact) { return "No such contact"; }
  if(!contact.hasOwnProperty(prop)) { return "No such property"; }

  return contact[prop];

}


Refactoring Process

First solution before refactoring:


function lookUpProfile(name, prop){
  for(var i = 0; i < contacts.length; i++) {
    var contact = contacts[i];
    if(contact.firstName == name) {
        if(contact.hasOwnProperty(prop)) {
          return contact[prop];
        } else {
            return "No such property";
        }
    }
  }
  return "No such contact";
// Only change code above this line
}

I'm working through the Free Code Camp's JavaScript curriculum as a refresher. This problem came right after the loop section which is why I used a loop here instead of map or filter. The official solution also uses a loop, because this is before we are expected to know of anything more advanced.

I used guard clauses to get rid of the if/else statements. Then I paired with a much more experienced dev who helped me refactor further by introducing me to the array.find arrow function. Cool!