Hello,
it’s my first time posting something in this forum…so hi everybody.
Could someone help me out with my code below? I don’t know why it is not working. Checked “Get Hint” on the challenge page. The code there is a bit different, but can not find out why.
//Setup
var 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 (var i = 0; i < contacts.length; i++) {
if (contacts[i].hasOwnProperty(prop)) {
if (contacts[i].firstName === name) {
return contacts[i][prop];
}
else {
return "No such contact";
}
}
else {
return "No such property";
}
}
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
Your code has two main “logic” issue that affect the outcome, even if it looks similar to the one in the hint section:
1 -
if (contacts[i].hasOwnProperty(prop)) {
if (contacts[i].firstName === name) {
return contacts[i][prop];
}
else {
return "No such contact";
}
The above piece of code can be read as:
“If this contact has this props, but the name don’t match means there is no such contact”
But how can you tell there is not that contact, if you haven’t checked them all yet?
Perhaps is better to assert that the contact doesn’t exist only after having checked them all.
2 -
if (contacts[i].hasOwnProperty(prop)) {
if (contacts[i].firstName === name)
You check that the prop exist, before checking that the contact name exist in the list.
This means that If I check for a totally fake name and prop, your program will just output
Hello @Marmiz,
Thx for your help.
I changed the code and thought I got it but there seems to be still something wrong. I read through it several times and even compared it with the code from the hints section. I can not find out where the mistake is.
for (var i = 0; i < contacts.lenght; i++) {
//when name exists
if (contacts[i].firstName === name) {
//and prop exists
if (contacts[i].hasOwnProperty(prop)) {
//return value of prop
return contacts[i][prop];
}
//when name exists but prop doesn't return "No such property"
else {
return "No such property";
}
}
}
//when all of the above checks fail return "No such contact"
return "No such contact";