Shen Adrien Shen Adrien - 2 months ago 9
Javascript Question

Difference between if else validation methods

Is there a pro or con to doing simple validation one way or another? What is the best practice? When would you use one over the other?

first method:

if ( <validate> ){
submitForm();
} else {
alert('Error');
exitFn();
}


second method:

if ( !<validate> ){
alert('Error!');
exitFn();
}

submitForm();

Answer

You're actually asking two separate questions:

  1. In an if-then-else structure, in general should I handle error conditions first and normal flow second, or vice versa?

  2. If I handle error conditions first, should I return after handling, or put the normal flow logic in an else block?

Both of these are matters of personal taste. Having said that, I think you would find that many programmers would put the error handling first. On the second point, opinions are split. Here is a question on this topic.

By the way, I don't know what you mean or intend with exitFn(). There is no such capability in JS.

My personal preference, and that's all it is, would be:

if ( !<validate> ) {
  alert('Error!');
  return;
}

submitForm();

The advantage here is that the error handling is usually shorter and it's better to get it out of the way as soon as possible, rather than force someone reading your code to go down a dozen or two dozen lines to see how (or if) errors are being handled; also, putting the normal flow within the if will add an extra level of indenting.