Hi All!
It’s been a while! I haven’t had time to do my coding for a bit, so going back over all the basic JavaScript before I try to tackle more complex exercises such as those to do with Fibonacci sequences.
Before I post my code with the question, here is my question up front - it is a bit swamped in the code otherwise.
Question 1: Why does (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) not work here? What is wrong with using the && operator? I get this wrong every time and I don’t understand why it needs to be split into two consecutive ‘if’ statements.
I would really like an answer to this question if possible as it is severely affecting my ability to be able to write code that works.
Question 1a: As an aside to this, why does writing the statement the other way around not work? What I mean is, usually I start this exercise with name === contacts[i].firstName instead of having name on the right hand side. I only change name to the RHS after I check the hints and see it does not work with name on the LHS. Is there a reason for this?
I feel if I could have a definitive answer to these questions I would be better able to write code which works.
So I am hoping there is an answer, and it is not just “one of those things”. I have a feeling that it will be just one of those things though.
// 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) {
if (contacts[i].hasOwnProperty(prop)) {
//MY QUESTION - why does (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) not work here? What is wrong with using the && operator? I get this wrong every time and I don't understand why it needs to be split into two consecutive 'if' statements.
return contacts[i][prop];
} else if (prop !== contacts[i].firstName || prop !== contacts[i].lastName) {
return "No such property";
}
}
} return "No such contact"
// Only change code above this line
}
console.log(lookUpProfile("Harry", "likes"));
console.log(lookUpProfile("Kristian", "lastName"));
console.log(lookUpProfile("Bob", "number"));