Can someone help me understand why this solution doesn’t work for the Profile Lookup:
for (let i = 0; i < contacts.length; i++){
if (name == contacts[i].firstName && contacts[i].hasOwnProperty(prop) == true){
return contacts[i][prop];
} else {
return "No such property";
}
return "No such contact";
}
Do we have to use a nested if statement, or can we use the “and” statement like I did?
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
It is best to use the Ask for Help button so we get a link to the challenge.
A return statement immediately stops a function. Also, the logic of your else isn’t quite right. That else will always run when the if condition is not true.
Isn’t that true of the posted solution as well? The only difference is that I’m using an and value instead of a nested if.
With either “and” or a nested if, if we hit get a value of i that matches the conditions, the loop stops and we get taken out of the function, right? I’m having trouble seeing what’s changing between the two.
It’s OK to return early if you return early in the right places. You are bailing out of the function too early in the case where you say no matching contact exists. You can’t say that no contact matches inside the loop that checks all contacts.
Oh ok. I see, the nested if allows me to check if there is a contact in the whole list of contacts with the given name before then seeing if that contact (assuming it exists) shares the given property.
By contrast, what I was doing was just checking whether the first contact in list had both the given name and property, and if it didn’t have both, I was returning “No such contact.”