Iterating through an array of objects and using if else statements

edit: i already noticed what my problem was, if you use return even inside of an if statement it exits the entire function and since the function runs through that part before doing the rest it ends up calling that code prematurely as expected

i’m basically stuck with this freecodecamp challenge:

javascript-algorithms-and-data-structures/basic-javascript/profile-lookup

i dont understand why when i place the return statement outside of the for loop it works but when i place it with an else statement outside of the first if statement it messes up with the function :frowning_face:

my solution with the else statement outside my outer if statement (i dont understand why doesnt this work)

function lookUpProfile(passedInName, prop) {
  for (let count = 0; count < contacts.length; count++) {
    if (contacts[count]["firstName"] === passedInName) {
      if (contacts[count].hasOwnProperty(prop)) {
        return contacts[count][prop];
      } else {
        return "No such property";
      }
    }
    else return "No such contact";
  }
}

solution with the statement outside of for loop (the one that works)

function lookUpProfile(passedInName, prop) {
  for (let count = 0; count < contacts.length; count++) {
    if (contacts[count]["firstName"] === passedInName) {
      if (contacts[count].hasOwnProperty(prop)) {
        return contacts[count][prop];
      } else {
        return "No such property";
      }
    }
  }
   return "No such contact";
}

Next time when you are posting code, select it and use the </> button in the post editor

Well, consider what happens inside the loop… you have an if ... else ... chain, it means that one of the two it will be executed, both have return statements inside, that means that something is returned from the function at first iteration of the loop and the loop never go to the iteration with higher values of i.

yes i already noticed thx though !