It's my first time asking a question here, so I apologize if the question has been repeated earlier.
This is my official solution for freeCodeCamp JS problem:
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 && contacts[i].hasOwnProperty(prop)){
return contacts[i][prop];
}
else {
return "No such property"
}
}
return "No such contact";
}
console.log(lookUpProfile("Kristian", "lastName")); //Output: No such property
And this is the official solution with changes in the 'nested-if' loop:
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";
}
console.log(lookUpProfile("Kristian", "lastName")); //Output: Vos
Why am I getting different solutions even if the logic behind nested-if in the official solution is similar to mine?
return
statement will terminate the function, regardless of whether it is inside a loop or not. If you have areturn
in both theif
andelse
branches, then it will always encounter areturn
, so your loop will never iterate more than once.return
in both branches which can be resolved by simply removing theelse
. There likely is a better dupe. I definitely have seen this problem a few times before.