Profile_Lookup Help

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.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

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.

If the return statement stops a function, doesn’t that mean we would need to create another function in order to get both statements?

Not at all… You need the return statements in the correct places guarded by the right conditional logic.

What do you mean by “stops”? I’m not understanding the importance.

If your function returns inside of a lop, the loop doesn’t do any more iterations. The function immediately returns the value.

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.

In your case if the name doesn’t match, the else statement is executed, which is not when you want the else statement to execute, is it?

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.”

1 Like

no, for the structure of your if/else the no such contact is never executed, it always stops at no such property. check your function output

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.