JS Basics - Profile Lookup Challenge (exercise 104 of basics)

am I a bad programmer if I solved the exercise like this?

function lookUpProfile(name, prop) {
  // Only change code below this line
  let counter = 0;
  for (let i = 0; i < contacts.length; i= i + 1) {
    if (contacts[i].firstName == name && prop == "lastName") {
      return contacts[i].lastName;
  } 
    else if (contacts[i].firstName == name && prop == "likes") {
      return contacts[i].likes;
  } 
    else if (contacts[i].firstName == name && prop == "number") {
      return  contacts[i].number;
  } 
    else if (contacts[i].firstName !== name) {
      counter = counter + 1;
  }
    else if (contacts[i].firstName == name && prop !== "number" && prop !== "likes") {
      return "No such property";
  } 
   if (counter == 4) {
    return "No such contact";
  }
}
  // Only change code above this line
}

lookUpProfile("Bob", "number");

You’re not a bad programmer, you are just beginning your JS journey and thus making some “mistakes” that a more advanced JS programmer wouldn’t make.

if (contacts[i].firstName == name && prop == "lastName") {
      return contacts[i].lastName;
  } 
else if (contacts[i].firstName == name && prop == "likes") {
      return contacts[i].likes;
} 
else if (contacts[i].firstName == name && prop == "number") {
      return  contacts[i].number;
}

What you’ve done here is hard coded the property names into these checks. And that works for this particular lesson because you know there are only three properties you need to check for. But what if each of these objects had 20 properties in them? Would you really want to create an if block for each one? Or what if you didn’t know in advance all of the possible property names? The property you need to check is being passed into the function using the prop parameter. If it could potentially be anything and you just need to check if it exists, how would you do that?

Also, the fewer “helper” variables you need, the cleaner your code will be, which will help reduce the chance of bugs. You can completely remove the need for your counter variable if you change the logic around in your function just a little.

Now that you have a working solution, I would challenge you to rewrite it without hard coding the property names and getting rid of that counter variable.

3 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.