Profile Lookup Exercise - Basic Javascript

Profile Lookup Exercise - Basic Javascript
0
#21

Ok now it works. Thanks a lot. It got really confusing there.
I need to understand one more thing. Why is the return “No such contact” outside the for loop? Is there any other way to do this?

0 Likes

#22

Only once you have made it through the entire contacts array (without a return statement executing) can you know for sure the contact does not exist.

1 Like

#23

Alright. Thanks for clarifying.

0 Likes

#24

Just one more thing. Could I have done it without using Nested if?
If i could go on with my style of code and evaluate the two statements in one if? Will i get the desired output?

0 Likes

#25

I do not see that you are currently using a nested if. If you have code with a nested if, you will need to post it first, so I can answer your question.

Currently, your code has a single if statement with two conditions. A nested if would look like:

if (some condition) {
  if (another condition) {

  }
}

0 Likes

#26

Here’s my new code. I am almost there. Every check is passed except for one:

function lookUpProfile(name, prop){
// Only change code below this line

for (var i = 0; i < contacts.length; i++) {

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

else if (contacts[i].hasOwnProperty(prop) !== true) {
    return "No such property";
}


}

return "No such contact";
// Only change code above this line
}

// Change these values to test your function
lookUpProfile("Akira", "likes");
0 Likes

#27

I am getting this error: “Bob”, “potato” should return “No such contact”

0 Likes

#28

That is correct, because your first if statement evaluates to false, so your else if statement is evaluated next. Since prop is “potato” and the first contact (contacts[0]) does not have a “potato” property, you return “No such property” and the function exits.

EDIT: I would suggest a nested if like the one I showed in a previous reply. The outer if would make sure the firstName property matches name. The inner if would check if the property exists for that object.

0 Likes

#29

Ok. So how do i fix it?

0 Likes

#30

See my edited last response.

0 Likes

#31

Ok, so basically the nested if is inevitable. Thanks.

0 Likes

#32

Not inevitable. You can solve it with an if/else if statement, but you would be repeating the same condition name == contacts[i].firstName, which makes the code not as concise and less readable.

0 Likes

#33

Yes, that’s true. Well I have to admit. This was the toughest challenge in Basic Javascript.

0 Likes