Profile Lookup Challenge Problem

Hi everybody. I’ve tried to look a similar code to mine but I have not found anything, so I’ve created this topic:

This is the challenge: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup.

My solution doesn’t work:

function lookUpProfile(name, prop){

// Only change code below this line

    for (var i = 0; i < contacts.length; i++) {

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

            return contacts[i][prop];

        } else if (contacts[i].firstName !== name) {

            return "No such contact";

        } else if (!contacts[i].hasOwnProperty(prop)) {

            return "No such property";

        }

    }

// Only change code above this line

}

lookUpProfile("Akira", "likes");

This is how the code works:

function lookUpProfile(name, prop) {
  for (let x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
}

Why my code doesn’t work with a && operator in a if statement but it works with nested if statements? Sorry if my doubt is so easy.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Just looking at your code, there is a logic problem here:

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

So, if it doesn’t pass the first test, it goes onto this test and if the name doesn’t match, that’s it, game over, we assume that it doesn’t match the first name on any record and return out of the function. This is on the first iteration of the for loop.

The other one works because it is fundamentally different logic. For example, the return "No such contact"; is outside the for loop so it isn’t going to get checked hit after every record is checked. Yours will never get passed the first record. If my thinking is right, you will never get passed the first iteration. Your first checks A && B, the next checks !A and the last checks !B. One of those will always be true (if A && B is false, that means that either A or B must be false).

You need to rethink your logic. Don’t get discouraged. Yeah, this stuff is weird and takes a while to learn how to think this way.

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