Return a function for IF ELSE IF statements

Viewed 372

I am trying to run a block of code that is series of IF ELSE IF statements, that checks to see if certain conditions are true.

    if (2 > 1) {
        return true;
    }

    else if (3 > 1) {
        return true;
    }

    else if (4 > 1) {
        return true;
    }

    else {
        alert('Not all conditions are true')
    }

It is working fine, but I want to add a function at the end, if all the conditions are true, In the code below I added the function, but now it seems to run the function without checking all the conditions first

    if (2 > 1) {
        return true;
    }
    else if (3 > 1) {
        return true;
    }
    else if (4 > 1) {
        return true;
    }
    else {
        alert('Not all conditions are true')
    }

    // Run this function after checking all the conditions are true
    allConditionsTrue();

I think I am getting confused with where the function should be placed.

Any help is greatly appreciated :)

3 Answers

For an arbitrary count of condition and with an immediate exit if one previous condition is false and the next is true, you could take a variable for the state if someFalse value occurs.

Afetr checkin all conditions check someFalse and return with 'Not all conditions are true'.

Finally it is clear, that all conditions are true and you can call a function for this case.

function check(value) {
    function allConditionsTrue() {
        console.log('All conditions are true');
    }
    
    let someFalse = false,
        conditions = [value < 2, value < 3, value < 4],
        fn = c => c ? someFalse : !(someFalse = true);

    if (conditions.some(fn)) return true;

    if (someFalse) {
        console.log('Not all conditions are true');
        return false;
    }
    
    allConditionsTrue();
    return true;
}

console.log(1, check(1));
console.log(2, check(2));
console.log(3, check(3));
console.log(4, check(4));

Take a look at && (AND) and || (OR) operators:

 if (2>1 && 3>1 && 4>1) {  
      allConditionsTrue(); 
      return true; 
   } else { 
     alert('not all conditions true'); 
   }

You placed the function call outside of all the checks so it is independent of the conditions. You can give it its own if block like:

if (2 > 1 && 3 > 1 && 4 > 1) {
  allConditionsTrue()
}

Or if you don't want to rewrite all the checks then you can create an array to hold their respective values like

let conds = [false, false, false]
if (2 > 1) {
    conds[0] = true
}
if (3 > 1) {
    conds[1] = true
}
if (4 > 1) {
    conds[2] = true
}
if (!conds.some(v => !v)) { // all are true
    allConditionsTrue()
}
if (conds.some(v => v)) {
    return true
} else {
    alert('Not all conditions are true')
}

Edit: corrected with suggestion from comment

Edit 2: an improvement

Related