Home > OS >  Understand why an else command is in a different position
Understand why an else command is in a different position

Time:03-14

I'm studing Javascript with FreeCodeCamp, till now everything is clear but I've a stupid question that I'ven't understood:

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

Why return "No such contact"; is after the for cycle and not the if that control the contact name?!

CodePudding user response:

If the return "No such contact"; would be in the else branch of the if (contacts[x].firstName === name), the function would stop processing the names after the first name in the contacts array is not the one you are searching for with the function:

lookUpProfile(name, prop)

But as it's written, it will return "No such contact" only when all contacts array names are checked. That's why it has to run the for cycle completely through to be able to tell if the name you are searching for is not in the contacts list.

CodePudding user response:

@picerno, That is because of the function (method) which has a return value, just for more explanation functions can have return type or void which is not return anything for the caller

so, here your function lookUpProfile(name, prop) returns string so in the function return keyword must have and return the value of the return contacts[x][prop];, or string return "No such property"; or return "No such contact";

for the Why part of your question, the loop provide the return keyword but take it like this, which is not an academic way of saying it but I do it anyway, The compiler says "I know you have provided return but I don't know if it has any Run-time error and doesn't return the value at all". In C# compiler it shows you Severity Code Description Project File Line Suppression State

  string test()
    {
        for (int i = 0; i < 5; i  )
        {
            if (i == 3)
            {
                return i.ToString();
            }
        }
    }

**Error CS0161  'ClassName.test()': not all code paths return a value** 

in C# it counts as a Compiler error, meaning it doesn't let compile unless you fix that.

Basically, it doesn't let you in some compilers like C#, for guaranteeing the function returns a value.

Hope I explained a little bit, please upvote the answer if you liked :)

  • Related