Can anyone explain why this works - Profile Lookup exercise

I got the first if to work after I put it inside the for loop (I get what’s going on here). When I wrote the second if (also inside the for ), it came back as correct, but it invalidated the first if. When I put it outside the for it worked, yet I have no idea why.

//function lookUpProfile(name, prop) {
  // Only change code below this line
  for(let i = 0; i < contacts.length; i++) {
     if(contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
    return contacts[i][prop]
    } 
  }// for
if(name !== contacts) {
  return 'No such contact'
}

A return statement immediately stops your function.

2 Likes

So when the return of the second if was inside the for, the first if was not read?

No. The first if was read just fine. But the very first time your code reaches a return statement the entire function stops. So the first time you encounter a name that doesn’t match, the return statement declaring that zero matching names exist triggers.

1 Like

Got it, thanks. Now that I’m redoing the exercises and not looking at the answers I can tell that there are things that I get or am on the cusp of understanding, and other stuff that I’m totally oblivious to. Thanks for reeling me back in on the previous tread.

So, this is one of those things where you just gotta keep the mind-spaghetti straight. While having a clear idea of what/how I wanted to accomplish on this one, I messed with some &&, and ‘tried’ to use some ternary (you totally can… see: spaghetti)… ultimately, making it as verbose/simple as possible is what helped me make sure all the logic was sound.

tl;dr when in doubt, rewrite all your ifs/elses to be as simple as possible and try to avoid stuff like && which can make it a bit confusing to keep straight when you are mentally doing a ‘step through’ routine…

Hi boondogle. I agree, though I think I got the hang of it ( &&s, ||s, that is). I wasn’t interpreting the ‘No such property’ if correctly and thought it was an issue with something else.

This stuff is hard. It all works out in the end with enough time and practice and patience.

Indeed. I think the psychological side of things is a big factor. It always feels like I’m floating in space, like “what the heck am I doing?” And you want to start working, and cannot say when, so that’s stressful. You just gotta keep at it.

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