I am trying to complete profile lookup and came up with a solution but not able to figure where I am wrong. I tried searching the forums and this seems by far one of the most posted questions. I wanted to make this post if someone can please help me with my solution, I can know where I am going wrong
My Solution
function lookUpProfile(name, prop){
// Only change code below this line
for(var i =0; i<contacts.length;i++){
if(contacts[i].firstname === name && contacts[i].hasOwnProperty(prop) === true){
return contacts[i][prop];
}
else if(contacts[i].firstname === name && contacts[i].hasOwnProperty(prop) === false){
return "No such property";
}
else {
return "No such contact"
}
Imagine the iterations: If for i == 0 name is not maching, then pass to else if, so name is not matching again, then pass to next else and returns "No such contact".
Yeah, think about how you want to get through that loop. Think about where those return statements should be. Actually walk though an example, tracing it through the code. This is a great skill to learn. If you need to, put in console.log statements to help.
And don’t get discouraged. A lot of people struggle with this one. But the struggle is worth it.
Thank you! Yes I get it now what you are sayin , I moved my last return statement out of the for loop so that solves the problem for iteration and the function code does not hit “No such contact” so the function still remains active. But I am going through iterations and still not able to get why the code would stop now? If any of the first names are in the array, it should atleast run one of the if else conditions and depending on if prop is present, it can return based on the condition
function lookUpProfile(name, prop){
// Only change code below this line
for(var i =0; i<contacts.length;i++){
if(contacts[i].firstname === name && contacts[i].hasOwnProperty(prop) === true){
return contacts[i][prop];
}
else if (contacts[i].firstname === name && contacts[i].hasOwnProperty(prop) === false){
return "No such property";
}
else {
}
}
return "No such contact"
}
I’ve always found it a lot clearer to write a separate function to look up the contact first:
function lookUpContact(name) {
for(contact in contacts) {
if(contact.firstname === name) {
return contact
}
}
function lookUpProfile(name, prop){
let contact = lookUpContact(name)
if (!contact) {
return "No such contact"
}
if (!contact.hasOwnProperty(prop) {
return "No such property"
}
return contact[prop]
}