Problem. js basic * 101

why not let me use && instead of having to nest IF?

it should have to work, I don’t see why and I’ve already tried every possible way and it gives an error for that topic.

if (contacts[i].firstName === name) {
    if (contacts[i].hasOwnProperty(prop) === true) {
    return contacts[i][prop];                                                                                                                            
   if (contacts[i].firstName == name && contacts[i].hasOwnProperty(prop) ===true) {                                                                                                                                                                              
      return contacts[i][prop]; }

why are these 2 not the same?

**Información de tu navegador:**

El agente de usuario es: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36

Desafío: Búsqueda de perfiles

Enlaza al desafío:

Both if statements are equivalent (although you nested the 3rd within the 1st if statement and used == instead of ===, but I assume that is not your actual code).

Could you please post the complete function?

PS. Instead of writing if (thisIsTrueOrFalse === true) you should simply write if (thisIsTrueOrFalse), there is no difference.

PPS. You don’t need hasOwnProperty. This is only useful if you want to know if a property belongs to an object itself or its prototype, so contacts[i][prop] is ok if contacts[i] exists (if you want to be super fancy, check out the optional chaining operator).

1 Like

the one above is the wrong one and the one below the one that works

I also have the doubt why in the correct one the last Return needs to be outside the loop

I also tried with:

else if (contacts[i].firstName !== name && contacts[i][prop]) {
return "No such contact";

Well what happens in your function if you check for lookUpProfile("Sherlock", "likes")?

  • enter loop, i is 0
  • contacts[0].firstName is Akira, so not Sherlock
  • function returns No such contact

Return statements terminate a function, so the loop ends immediately, before even checking the other entries in the contacts array.

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