Basic JavaScript: Profile Lookup - A Few Questions

Hi all,

I really don’t understand why this works (return outside the for loop):

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

But this doesn’t (return inside for loop)?

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

I also have a couple of syntax questions. Do else statements require {} after them or not? Why does contacts.i.firstName not work despite the fact firstName is only one word?

Thanks in advance!

That return inside the for loop I believe is going to stop the execution of the loop before the loop finishes.

All if, else, and else if needs to have the curly braces {}

Thank you so much to the both of you. I am understanding it now.

Especially with the for loop. When it’s something that might be found on a second, third etc. iteration, you can’t return in the loop because it’ll never get there.

So you basically have to play with the fact that if it exits the for loop and executes whatever is below that afterwards, it’ll be because it hasn’t found it, so you can safely return the error message there.