Why does it only work outside for loop?

Hello! I have this code that I wrote for the profile look up challenge in the basic javascript course. I am not sure why the code works when I place the “return “No such contact”” outside of the for loop, but not when I place it inside of it. Here is the code:

// 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(name, prop) {
  // Only change code below this line
  for (var i = 0; i < contacts.length; i++) {
      if (contacts[i]["firstName"] == name) {
          if (contacts[i].hasOwnProperty(prop)) {
              return contacts[i][prop];
          }
          return "No such property";
      }
      return "No such contact";
  }
  // Only change code above this line
}

lookUpProfile("Akira", "likes");

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Suppose you put the “no such contact” return inside the loop. Logically, you’d want that to fire off when the contact name doesn’t match, right?

But if you do, then in every case we are returning a value based on the first record only. If the first record has the wrong name, we’re immediately returning “no such contact.” If the name does match but this first record doesn’t have the requested property, we immediately return “no such property.” Otherwise, we return the value of that property from that first record.

The issue here is, we need to be able to check names against all records. Only if we loop over them all and don’t find a match should we return “no such contact.” So moving that return after the loop allows all records to be checked for name, by not exiting early from the loop.

1 Like

Ok, thanks for the nice and detailed response!(:

1 Like

Alright, will definitely do in the future!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.