Can you tell me what I did wrong? Profile Lookup

Can you tell me what I did wrong? Profile Lookup


Hi all,

I figured out the answer to the Javascript Profile Lookup exercise, but I can’t figure out why this is wrong:

function lookUpProfile(firstName, prop){
for (var x = 0; x < contacts.length; x++){
if (contacts[x].firstName === firstName) {
if (contacts[x].hasOwnProperty(prop)) {
return contacts[x][prop];
} else {
return “No such property”;
else {
return “No such contact”;

It did’t like the last else statement, return “No such contact”;. I had to take out the brackets and place the return statement outside the for loop. Can anyone tell me why?



Because your first if statement goes through objects and checks if (contacts[x].firstName === firstName) if it is not it executes else { return "No such contact"; } - it passes only if checked firstName is Akira.

When you move else statement outside the for loop it is reached only when for loop is finished (i.e. all objects are checked and no firstName match is found).


Ah, got it now. Thanks so much!


I read this explanation and I’m still trying to make sense of it. I looked at this for hours and then decided to move around my closing brackets so that the return "No such contact"; was outside of the for loop but I’m not quite sure I get it. I knew that for some reason my for loop wasn’t getting past the first array item, but I couldn’t figure out why.

Is it that because the first item in the array satisfies the first two if conditions, it closes the loop and never iterates again?


If else is in for loop:

function lookUpProfile(firstName, prop) {
    for (var x = 0; x < contacts.length; x++) {
        if (contacts[x].firstName === firstName) {  // <-- if first name doesn't match..

           // ..this code doesn't matter..

        } else {  //  <-- ..execute this, return from function
            return "No such contact";

If firstName doesn’t match, return in else statement get executed - the function ends.


Here is my soluction
``` `for(var i=0;i<contacts.length; i++){
if(contacts[i].firstName === firstName){
if(contacts[i].hasOwnProperty(prop) === true){
return contacts[i][prop];
else if(contacts[i].firstName === firstName ||
contact[i].hasOwnProperty(prop) === false){
return “No such property”;
return “No such contact”;


can u explain a little bit further at this point? thank you in advance :smiley:


See the answer Nr.5

The first check in the first if statement will be if contacts[0].firstName (which is always Akira) is equal to parameter from the test case. If it isn’t, the program executes else statement which has return in it and therefore it ends the function.


That’s a great solution. Are we supposed to use the hasOwnProperty function or is there another way to solve the problem? I was initially thinking of using a while loop and checking each element via an if-statement.