So this is the code. I used the for loop for iteration of the contacts array. Then I used if statement within. It is in fact a simple one and it works fine as it should.
However, the for-loop is not iterating any further than the first object within contacts array, within this code and if I change the firstName in the lookup function, it directly goes to returning the string “No such contacts” which means it is simply skipping the code and the iteration is not working.
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) {
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"
}
} else {
return "No such contact"
}
}
}
console.log(lookUpProfile("Akira", "number"));
I looked up in the hints and found that the return statement “No such contact” needs to be eliminated as an else statement and moved outside the for-loop into the function like the following;
[spoiler] function lookUpProfile(name, prop) {
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"
} [/spoiler]
I would really appreciate if you could help me understand why is that. Thanks in advance.