Is there a better way to reduce multiple if statements?

refactoring if statements
replace multiple if statements in java
how to refactor multiple if statements javascript
how to avoid nested if statements in java
java 8 multiple if conditions
refactor multiple if statement c#
replace if/else with strategy pattern
best way to format multiple 'or' conditions in an if statement (java)

I have a function that validates few different conditions. Here is the example of my function:

function checkData() {
  var errorMsg = "",
    fld1 = 0, //Number(document.getElementById('fld1').value),
    fld2 = 5, //Number(document.getElementById('fld2').value),
    fld3 = 1, //Number(document.getElementById('fld3').value),
    fld4 = 0; //Number(document.getElementById('fld4').value);

  if (!fld1) {
    errorMsg += "Error 1\n\n";
  }

  if (fld1 === fld4) {
    errorMsg += "Error 2\n\n";
  }

  if (fld2 > fld4) {
    errorMsg += "Error 3\n\n";
  }

  if (fld3 > 3) {
    errorMsg += "Error 4\n\n";
  }

  if (errorMsg !== "") {
    var check = confirm(errorMsg + "\n Do you want to submit the form?");

    if (check) {
      return true;
    } else {
      return false;
    }
  }

  return true;
}
<button onclick="checkData();">Click Here</button>

In this use-case I think the 'multiple-ifs' solution is quite clear so it is the one to use.

If you want to optimize a bit, I can only suggest

        if(check){
            return true;
        }else{
            return false;
        }

to become

return !!check;

(the two exclamatives simply cast any object to a boolean vale :-))

How to Replace Many if Statements in Java, Also, the switch statements do not fit well when there are complex conditions. Another side effect of having nested decision constructs is they  Alternative to Multiple IF Statements. This is a little unorthodox, but it’s pretty neat for something like this. Use INDEX and MATCH with array constants to map the matching values to the desired results. If you’re not familiar with a array constants, it’s pretty simple. Using the curly braces { and }, you can create the array constants of data.

The whole check variable is pointless. So return confirm is all that you need

function checkData() {
	var errorMsg = "",
		fld1 = 0, //Number(document.getElementById('fld1').value),
		fld2 = 5,//Number(document.getElementById('fld2').value),
		fld3 = 1,//Number(document.getElementById('fld3').value),
		fld4 = 0;//Number(document.getElementById('fld4').value);

	if(!fld1){
		errorMsg += "Error 1\n\n";
	}

	if(fld1 === fld4){
		errorMsg += "Error 2\n\n";
	}

	if(fld2 > fld4){
		errorMsg += "Error 3\n\n";
	}

	if(fld3 > 3){
		errorMsg += "Error 4\n\n";
	}

    return errorMsg !== "" ? confirm(errorMsg + "\n Do you want to submit the form?") : true

}
<button onclick="checkData();">Click Here</button>

Is there a better way to reduce multiple if statements?, In this use-case I think the 'multiple-ifs' solution is quite clear so it is the one to use. If you want to optimize a bit, I can only suggest if(check){  After that, we can use them either in the nested if statements or switch case statements. Alternatively, we can also use them as a factory of objects and strategize them to perform the related business logic. That would reduce the number of nested if statements as well and delegate the responsibility to individual Enum values.

You could refactor your if statements using the ternary operator. But chances are that it would make your code far harder to read. You could replace

if(check){
    return true;
}else{
    return false;
}

With just return check; as this is a boolean statement anyway.

Also, as far as readability goes it would be nice to label your field variables something more meaningful, as knowing that fld2 should always be greater than fld4 isn't immediately obvious from the name.

And if you don't care about highlighting the specific error codes then you could of course merge some of your checks together and just return false without the error codes specified, but I suspect you will want to keep that functionality.

Stop Putting So Many If Statements in Your JavaScript, The most popular way of handling conditional logic is the if statement. Ternary operators are a great way to handle basic if-else conditions. Using nested IF function will take too much time. We can use alternative function i.e. CHOOSE function to return the same output that IF function will return. Choose: Returns the character specified by the code number from the character set for your computer. CHOOSE function will return a value from a list of values based on a given index number.

Code Smells: If Statements, We're going to start with (more or less) the version of this method that has There's only one else , which actually follows one of the if statements with to identify the code that manages the looping, and replace those pieces  How to reduce the number of if else statements in PHP? My tips are as follows: 1.Use a switch statement when it is suitable; 2.use exit() statement when it is feasible; 3. Use ternary statement when it is feasible;

Keeping your code clean by sweeping out "if" statements, else { throw new IllegalArgumentException("Error type not supported: " + errorTypeString); } } Are you more comfortable dealing with "if" statements? Clarity is vital, but this simple rule of reducing "ifs" (in the way you  For more information, please see Excel IFS function instead of nested IF.. CHOOSE instead of nested IF formula in Excel. Another way to test multiple conditions within a single formula in Excel is using the CHOOSE function, which is designed to return a value from the list based on a position of that value.

Alternative to Multiple IF Statements, Ever notice how crazy it looks with all those parentheses and it's difficult to follow​? Well, I was wondering if there was another way I could create a  Although the latest version of Excel can accommodate a lot of IF functions, multiple IF statements are not the best solution, try to avoid it as much as possible. The IFS function is an improvement for multiple IF statements provided by Microsoft, able to analyze up to 127 criteria.

Comments
  • In this use-case I think the 'multiple-ifs' solution is quite clear so it is the one to use.
  • @MarcoS is correct. Doing anything fancy, here, would only confuse anyone else trying to figure out what the code is doing
  • Agree with @MarcoS. I'm voting to close this because the code looks fine as it is. Even if any changes are suggested they'll be trivial which won't add any value to the site or future visitors.
  • Why double ! ?
  • You convert any argument (null, undefined, 0, etc.) into a boolean with !check. The problem now is that you inverted the boolean, so if it evaluated to true before, you have false now. Using two exclamation marks, !!check will get you the initial condition of your boolean. See this answer for more details: stackoverflow.com/a/784946/4791226