I understand that there are many easier and shorter ways of solving it but I want to grasp the concept behind the 2nd function in such a scenario. Solutions should be in the 2nd function format only and should be accompanied by a detailed explanation.
The logic
- I have an array of objects representing different people in a contacts list.
- The function should check if name is an actual contact’s firstName and the given property (prop) is a property of that contact.
- If both are true, then return the “value” of that property.
- If name does not correspond to any contacts then return the string No such contact.
- If prop does not correspond to any valid properties of a contact found to match name then return the string No such property.
The object array
const contacts = [
{
firstName: "Akira",
lastName: "Laine",
number: "0543236543",
likes: ["Pizza", "Coding", "Brownie Points"],
},
{
firstName: "Harry",
lastName: "Potter",
number: "0994372684",
likes: ["Hogwarts", "Magic", "Hagrid"],
}
]
1st function (Correct)
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";
}
lookUpProfile("Akira", "likes");
2nd function (wrong)
function lookUpProfile(name, prop) {
for (let x = 0; x < contacts.length; x++) {
if (name === contacts[x].firstName && contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
}
if (name !== contacts[x].firstName || contacts[x].lastName) {
return "No such contact";
}
if (prop !== contacts[x][prop].name) {
return "No such property";
}
}
}
lookUpProfile("Akira", "likes");