Why have to nest if else

Tell us what’s happening:
Hi everyone, I am just confused why the if-else statement will trigger a fault?

  **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){
      return contacts[i][prop];
      return "No such property";
    return "No such contact"; */
for(let 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 && contacts[i].hasOwnProperty(prop)){
    return "No such contact";
  }else if (contacts[i]["firstName"] === name && !contacts[i].hasOwnProperty(prop)){
    return "No such property";
// Only change code above this line

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

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36

Challenge: Profile Lookup

Link to the challenge:

In the comment code you wrote, the last return should be embeded inside the function’s curly braces not out of it.
And it will work.

Hi Zak, thank you for your response . Yes you are right, I just comment it because of I want to figure out why the if… else statement not work in this senario.

I tried the if else chain at that challenge and i was lost for while on why it gives weird results. It turned out that if you have a condition and a opposite condition, you should use just one if statement with first condition and a statement then write the second statement that should execute for the opposite condition, out of the first if statement so that it will execute incase the first if statement’ s condition was false.
You should remember that if else if chain work if you have multiple conditions that are not opposite to each other, otherwise you should just do what i said in the first paragraph.
In my humble opinion.
Happy coding.

1 Like

I would suggest you log out the loop index for both versions of the code. Consider what happens if the name you are looking for is not found on the first iteration of the loop.

Why would this call work lookUpProfile("Harry", "likes") if the “Harry” object was the first object and not the “Akira” object? And vice versa.

1 Like

thank you zak, you are the man. Now I get it

1 Like

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