javascriptif-statement

javascript if if else (not else if)


I have a simple bit of code that checks some conditions, and I want each condition to cause a unique output, but if no conditions are met then to cause another unique output.

Is there any way to create an else that is only triggered if all previous if statements fail? I am aware that the below code carries out the same purpose, but it seems cumbersome and it would be nicer to have a quicker way of checking all of the variables than copy and paste all of them into another if statement.

var boolean1 = true,
  boolean2 = true,
  boolean3 = false;

if (boolean1) {
  alert("boolean1");
}
if (boolean2) {
  alert("boolean2");
}
if (boolean3) {
  alert("boolean3");
}
/* and so on */
if (!boolean1 && !boolean2 && !boolean3 /* etc */ ) {
  alert("none");
}


Solution

  • To make this scale, you will need to change your data structure to something you can iterate over. That way your processing logic remains the same and you can supply any size input. Here's one implementation where I use an object with properties representation your Boolean values. The checkResults function below iterates over the property names in the object, checks the value for each one, and performs an alert and sets a flag if any value is true. At the end it checks if any value was true and alerts with that case.

    function checkResults(resultMap) {
        var any = false;
        Object.keys(resultMap).forEach(function(key) {
            if (resultMap[key] === true) {
              any = true;
              alert(key);
            }
        });
        if (!any)
          alert('none');
    }
    
    checkResults({
      'boolean1': false,
      'boolean2': true,
      'boolean3': false
    });

    You can build your input object property by property if you have to:

    var results = {};
    results['boolean1'] = true;
    results['boolean2'] = false;
    ...
    checkResults(results);
    

    And the checkResults function always stays the same.