Basic JavaScript - Profile Lookup doubt in 3 test cases

Tell us what’s happening:
I am not able to understand why my code does not work for the test cases where
the name is an actual contact’s firstName and the given property (prop ) is a property of that contact. It works if I nest if inside if but why does it not work when I use &&
Your code so far

// Setup
const contacts = [
{
  firstName: "Akira",
  lastName: "Laine",
  number: "0543236543",
  likes: ["Pizza", "Coding", "Brownie Points"],
},
{
  firstName: "Harry",
  lastName: "Potter",
  number: "0994372684",
  likes: ["Hogwarts", "Magic", "Hagrid"],
},
{
  firstName: "Sherlock",
  lastName: "Holmes",
  number: "0487345643",
  likes: ["Intriguing Cases", "Violin"],
},
{
  firstName: "Kristian",
  lastName: "Vos",
  number: "unknown",
  likes: ["JavaScript", "Gaming", "Foxes"],
},
];

function lookUpProfile(name, prop) {
// Only change code below this line

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

// Only change code above this line
}

lookUpProfile("Akira", "likes");
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Basic JavaScript - Profile Lookup

Link to the challenge:

Formatting for human-readablity:

function lookUpProfile(name, prop) {
// Only change code below this line

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

  return "No such contact";

// Only change code above this line
}
1 Like

It depends upon how you are using &&

I’ve edited and added the code with && which I am trying to use. Please look it and guide me.

This is your problem. A return statement immediately stops your function call, even in the middle of a loop.

1 Like

I get it but I am asking about this test case lookUpProfile("Kristian", "lastName")

this should be executed in the very first if statement with &&, but it skips that and does not goes inside it.

Because the loop never gets that far. The very first time you encounter a contact that has a first name that does not match, you immediately stop and return “No such contact”.

Also, you can’t use dot notation when the property name is stored in a variable, like prop here.

1 Like

Thanks a lot <3 Understood it now.
I guess it’ll take some time to wrap my head around it.
Again Thanks

1 Like