user1052591
user1052591

Reputation: 185

Javascript if condition with return

Folks, I am modifying a current function slightly to make use of two variables. I have shown the past and present versions in the code snippet.
Basically what I want is if either one of the two if conditions namely First Condition and Second Condition are are true, do not execute the remaining logic of the function. If both are false, continue with the remaining code of the function.
I think I am making a silly mistake somewhere and if the first condition is true, execution is stopping right there. (I Know that is because of the return statement at the end.) How do I make sure the second if condition as well even if first one was true and returned a return

function myAlgorithm(code1, code2) {

   if(eval(code1)) {

      if(First condition) {
         alert("You cant continue");

         return;
      }
    }

    if(eval(code2)) {
       if(Second condition){
         alert("You cant continue");
       return;
      }

    }

    //If both of the above if conditions say "You cant continue", then only
    //disrupt the function execution, other wise continue with the left
    //logic

    //Rest of the function logic goes here

}

Ealier this code used to be:

function myAlgorithm() {

   if((First Condition) && (Second Condition)){
    alert("You cant continue");

    return;
   }

  //Rest of the function logic goes here
}

Upvotes: 0

Views: 16262

Answers (2)

Declan Cook
Declan Cook

Reputation: 6126

Could use flag variables to keep track of your conditions and then check both of them like before

function myAlgorithm(code1, code2) {
 var flag1;
 var flag2
if(eval(code1)) {
  flag1 = First condition
}

if(eval(code2)) {
  flag2 = second condition
}

if(flag1 && flag2){
  return;
}
//If both of the above if conditions say "You cant continue", then only
//disrupt the function execution, other wise continue with the left
//logic

//Rest of the function logic goes here

}

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 174957

Use a variable and increment it once the condition is met. Then check to see if the variable was incremented.

function myAlgorithm(code1, code2) {
    var count = 0;
    if (eval(code1)) {

        if (First condition) {
            alert("You cant continue");

            count++;
        }
    }

    if (eval(code2)) {
        if (Second condition) {
            alert("You cant continue");
            count++;
        }
    }
    if (count == 2) {
        return "both conditions met";
    }

    //If both of the above if conditions say "You cant continue", then only
    //disrupt the function execution, other wise continue with the left
    //logic
    //Rest of the function logic goes here
}

Upvotes: 1

Related Questions