Profile Lookup exercice

Hello,
I know that solution is more simple, but someone could say me why the first condition (line 4) doesn’t work ?

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

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)) {
    return contacts[i][prop];
    } else if (contacts[i].firstName != name) {
    return "No such contact";
   } else if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop) == false) {
    return "No such property";
   } 
  }

what does it make you say that it doesn’t work?

Because when I launch the test, the résult is not ok when firstName and Prop are well:

1 Like

ok, let’s consider the first one with "Kristian", "lastName" as arguments
which of the if conditions is true when i = 0?

have you checked what it returns with a console.log?

console

No such contact ?

which condition is true tho?

do you understand why it is giving the wrong result?

I understand that it can’t works now but I looking for how to fix the problem.
The second one is true… then he go out of loop for.

if you where looking through the list of contacts yourself, when would you be able to say that there is no such contact?

is it possible with the 3 conditions or not ?
Otherwise I stopped looking for and I stay with the solution.

sorry I didn’t see you last answer.
After I = contacts.length

so, after you have looked through all the contacts.
In code, where is that?

when I get out of the loop

That’s it !

for (var i = 0 ; i < contacts.length; i++ ) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
     return contacts[i][prop];
        }  else if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop) == false) {
    return "No such property";
     } 
    }
return "No such contact";

// Only change code above this line
}

:smiley:

Have you a comment about this solution. something for improve it ? aside the right solution of course.

Thank you ilenia for your help

this is repeated twice in your code, it is not wrong, but you can find a way to have it written only once

I’m looking for…

The solution of freecodecamp, otherwise I don’t see.

for (var i = 0 ; i < contacts.length; i++ ) {
    if (contacts[i].firstName === name ) {
     return contacts[i][prop] || "No such property";
        }
    }
return "No such contact";

pretty similar to your solution, you could have had an if/else inside here

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