Javascript – If statement nesting vs && operator. (beginner problem)


(My solution 1 and the working solution in 2)
I have an issue with one line of code which doesn’t seem to be doing as expected (highlighted in bold below(1). It should check if name matches the firstName of the object && if the object has a property of prop – returning the property if both are true. However, this bit of code seems to be skipped over when running test as each result gives me the answer of "No such contact".
There is a solution below (2) which uses a nested IF statement but I want to know why my initial way of trying to solve it doesn’t work. Thank you in advance.

(Also, the problem in full can be accessed here
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup)

1)


// 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 (name === contacts[i].firstName && contacts[i].hasOwnProperty(prop)){
    return contacts[i][prop];
  }else if (name !== contacts[i]["firstName"]){
    return "No such contact"
  }else if (prop !== contacts[i]["prop"])
    return "No such property";
  } 

  // Only change code above this line
}
lookUpProfile("Akira", "likes");


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";
}

Source: JavaSript – Stack Overflow

November 21, 2021
Category : News
Tags: if-statement | javascript | nested | operator-keyword

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.