Tell us what’s happening:
No issue solving the challenge, I was able to do it in a way similar to solution 1 in the hint guide quite easily.
However, I realised that the code as-written would only work correctly if every contact had the exact same properties. If not, it would only check the first contact in the array with hasOwnProperty, see that it does, and move on.
It seemed to me that this wasn’t best practice as it wasn’t future-proofed against changes in the profile database format, so I wanted to find a way to make it work even if the contacts didn’t all have the same four properties.
After a lot of fiddling around, I got it working how I wanted! However, the code seems unnecessarily complex and clunky, and I was curious to see if anyone here can suggest a more elegant, streamlined way to solve this challenge while protecting against a situation where different profiles have different properties.
Thanks in advance for your ideas!
Your code so far
// 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
let contactProp;
let contactName;
for(let i=0; i<contacts.length; i++) {
if(contacts[i].firstName == name) {
contactName = i
if(contacts[i].hasOwnProperty(prop)) {
contactProp = i;
}
}
}
if(contactName != undefined) {
if(contactProp == contactName) {
return contacts[contactProp][prop]
}
else {
return "No such property";
}
}
else {
return "No such contact";
}
// Only change code above this line
}
lookUpProfile("Akira", "likes");
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36
Challenge: Basic JavaScript - Profile Lookup
Link to the challenge: