Basic JavaScript: Profile Lookup - A Few Questions

Basic JavaScript: Profile Lookup - A Few Questions
0

#1

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!


#2

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 {}


#3

Technically, if you only have one statement which needs to be executed after an if or else if or else, you do not need the { and }, but many linters will complain and/or not allow it (FCC’s linter will not allow it).

contacts is an array. It has indexes starting at 0 through the length of the array minus 1. When you use dot notation like contacts.i, there must be an actually property named “i” in contacts, but since it is an array, it does not have such a property name.


#4

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.


#5

I am not sure I follow what you are trying to describe, but what you need to understand is when a return statement is executed, the function is immediately exited and the value specified after the return keyword will be returned to the function call.