I am trying to solve a javascript exercise which gives me a fuction with two parameters(name, prop) AND an array with 4 objects, which each object has some properties, so i have to these tests:
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 "No such contact"
If prop does not correspond to any valid properties of a contact found to match name then return "No such property"
and I thought I had found two ways to answer a specific question, but one of them doesn't work and I really want to understand why.
The first code you're going to see works very well, and I already passed the test using this one, but the second one doesn't work and both seems almost equal, the only difference I can see is that in the first code I break the if into two pieces, which makes the second if only be achieved if the first if returns true
// First Code, this one works
function lookUpProfile(name, prop) {
for (var 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";
}
// Second Code, this one doesn't work
function lookUpProfile(name, prop) {
for(var x = 0; x < contacts.length; x++) {
if(contacts[x].firstName === name && contacts[x].hasOwnProperty(prop) == true) {
return contacts[x].prop;
} else if(contacts[x].firstName !== name) {
return "No such contact";
} else if(contacts[x].hasOwnProperty(prop) !== true) {
return "No such property";
}
}
}
The error message says that the --return contacts[x].prop; -- isn't returning the right values only in the second code.