JS if/else in a for loop question - "Profile Lookup" challenge

WARNING*

code below will answer this challenge, so if you don’t want a spoiler, don’t read below


I just finished the Profile Lookup challenge in the Java Script section. It took me a long time to figure this one out, but the last thing that hung me up was the final statement that returns “No such contact”

here is my code that wouldn’t work:

//Setup
var contacts = [
{
“firstName”: “Akira”,
“lastName”: “Laine”,
“number”: “0543236543”,
“likes”: [“Pizza”, “Coding”, “Brownie Points”]
},
{
“firstName”: “Harry”,
“lastName”: “Potter”,
“number”: “0994372684”,
“likes”: [“Hogwarts”, “Magic”, “Hagrid”]
},
{
“firstName”: “Sherlock”,
“lastName”: “Holmes”,
“number”: “0487345643”,
“likes”: [“Intriguing Cases”, “Violin”]
},
{
“firstName”: “Kristian”,
“lastName”: “Vos”,
“number”: “unknown”,
“likes”: [“Javascript”, “Gaming”, “Foxes”]
}
];

function lookUpProfile(firstName, prop){
// Only change code below this line
for (i=0; i<contacts.length; i++){
if (firstName == contacts[i].firstName) {

if (contacts[i].hasOwnProperty(prop)) {

    return contacts[i][prop];
  }

else {
return “No such property”;
}
{
}
}
}

else return “No such contact”;

// Only change code above this line
}

// Change these values to test your function
lookUpProfile(“Bob”, “likes”);

To make it work, I removed the “else” before “return ‘No such contact’;” - but I don’t know WHY that was stopping it from working. Shouldn’t the lase “else” relate to the first “if” statement? I guess if the firstName variable doesn’t equate to true in that first statement it just skips the rest and goes down to the last line of code and runs the way it should, but why does the “else” stop it from doing that?

Thanks.

@derekbmcintire Hi Derek, in this case you want the for loop to iterate over all the elements in the array before getting to return 'no such contact'. If you have return 'no such contact' within the for loop as an else paired with the first if, you will return ‘no such contact’ as soon as a contact is not found on an iteration over the elements in the array. As the if is within the for loop, any paired else would also have to be within the for loop.

In other words, the for loop will not iterate over the entire array and will instead return early. Getting rid of the last else and putting the return 'no such contact' outside the for loop means that the for loop first iterates over the entire array before finishing; if the if conditional is not met the for loop finishes without returning and the function executes the final return 'no such contact'.

Hope that helps ; )

@derekbmcintire BTW, top tip: when posting code on the forum you can use 3 backticks ``` before the code and 3 after to format it properly.

yes, I get it now! Thank you :slight_smile: