Profile Lookup - Need some help

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

for (let 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)) {
        return 'No such property';
    } 

      }


return 'No such contact';

// Only change code above this line
}

I was wondering can someone explain to me why do we put - return ‘No such contact’; - outside of the if statement.
I was thinking of placing ```

return 'No such contact'; with the else if (contacts[i].firstName === false)inside the if statement but it doesnt seem to work.

You are going to iterate through the whole array of objects, after the loop is done iterating and if none of the conditions in your if else if block statement are met, then you are going to return “No such contact”, that’s why you put it outside the scope of your loop.

function lookUpProfile(arr) {
// Iterate through the whole arr with a for loop
   for(let i = 0; i < arr.length; i++) {
       // First condition
       if(condition) {
         // If this condition is met, then return immediately
         // and end the function execution 
       } else if(second condition) {
              // If the first condition is not met, check for the second condition
              // If this condition is true, then return immediately
        }
    }
   // Now if none of the conditions of your loop are true and after
   // the loop is done iterating your arr, execute the code below
   return "No such contant";
}
2 Likes

The for loop go through all the contacts in the array and check each contact if it matches to the name you are looking for. If any of the contacts match the name, it checks if the contact has a property it return the contact and its property. The else if is reached if you find a contact match but it has no property so it return “no such property”
If all the for loop ends with no contact match, the program exit the for loop, reach the end of the function and return ‘no such contact’

For loop compares name to each contact
If name = contact and contact has property (exit the function and return name found and
property found)
if name = contact and contact has no property ( exit the function and return name found but
no property)
when for loop go through all the contact and dont exit by returning from the inside of the for because no contact found --> you add the return at the end that says no contact found.

1 Like

Thank you both for help, it’s makes perfect sense. These forums are a lifesaver.

2 Likes