JS - alternative to return false?

2

More than a question, it's a question that I want to read from those of you who have been bumping heads with this for a long time.

I am in JavaScript, I am doing a form validator and I see myself in the situation that I want to cut completely after a moment if the data that arrives is not correct.

I understand that putting a return in the middle of a function is not a very good idea. But now I'm in doubt about how to do it. And I have that doubt always.

Could someone tell me the alternative (practical, theoretical, whatever) of using RETURN FALSE to finish with the execution of a function? (Without having to use clear conditionals). And why would it be better?

Greetings and thanks

    
asked by José González 01.09.2017 в 13:48
source

1 answer

3
  

I understand that putting a return in the middle of a function is not very   good idea

It is a recommendation to make the code more readable, it is called "single point of exit" ( single exit point ). For example, if you modify a function and make a change, it may be that the change

For example, right now I have debugged an initialization function and, if the value of the configuration was null , I would do return null; in the middle of the code because there was nothing to do. Then I added more initialization code that always had to be executed and I left the return .

It can also affect the debugging facility.

The simplest alternative is to change the flow so that the check implies execution, that is:

function hola() {
   if (valor == 0) {
     return false;
   }
   // Hacer hola();
   return loquetoque;
}

go to:

function hola() {
   if (valor != 0) {
      // hacer hola();
      return loquetoque;
   }
   return false;
}

or similar varieties (put the return false in a else , put the value to return in a variable and only do a return , etc.)

In any case, the first thing is the clarity of the code, it is not a rule that must be followed blindly. In particular, making a series of return at the beginning of the code according to parameter checks can be a better idea.

function hola(par1, par2, par3, par4) {
   if (par1 == 0) {
      return false;
   }
   if ((par2 == 1) && (par4 ==5)) {
      return false;
   }
   if (par3 == 2) {
      return false;
   }
   return loquetoque;
   // hacer hola
}

before:

function hola(par1, par2, par3, par4) {
   if ((par1 != 0) || ((par2 != 1) && (par4 != 5)) || (par3 != 1) {
      // hacer hola
      return loquetoque;
   }
   return false;
 }
    
answered by 01.09.2017 / 14:05
source