Jason
Jason

Reputation: 415

Multiple javascript conditions

I making a condition in javascript that if a value or b value is greater than 59 and c1, c2, c3, c4 any of these are greater than 21 than my condition will be true. It's working fine but when I entering a value 50 b value 30 and c1 value 25 it is going to else statement.

Here is the code:

if((a > 59) || (b > 59) &&  (c1 > 21) &&  (c2 > 21) &&  (c3 > 21) &&  (c4 > 21)){
    total = a + b + c1 + c2 + c3 + c4;
}
    else {

    }

Can you guyz help me out how to fulfill my conditions?

Upvotes: 1

Views: 82

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

As per your comment

@UnholySheep I am making this statement like a or b should be greater than 59 and c1,c2,c3 or c4 should be greater than 21 than it would be true statement

This is what you are actually looking for:

(a > 59 || b > 59) && (c1 > 21 || c2 > 21 || c3 > 21 || c4 > 21)

This is how it works:

  • (a > 59 || b > 59) check whether a or b is greater than 59
  • (c1 > 21 || c2 > 21 || c3 > 21 || c4 > 21) is true if one of them is greater than 21
  • the && operator checks if both expressions are true, only in that case it returns true

let a=60,b=30,c1=30;

console.log((a > 59 || b > 59) && (c1 > 21 || c2 > 21 || c3 > 21 || c4 > 21));

Upvotes: 3

vsb
vsb

Reputation: 11

Assuming your expectations are right, then I would say your statement is wrong as per your expectations.

"I am making this statement like a or b should be greater than 59 and c1,c2,c3 or c4 should be greater than 21 than it would be true statement."

The "and" in your statment below is causing your expectations to fail. The first part "a or b should be greater than 59" is evaluating it false when a is 50 and b is 30.

The second part "c1, c2, c3 or c4 should be greater than 21" is evaluating to true when c1 is 25.

So, your whole condition expression inside the if(...) is boiling down to: false and true. This would always result in false thats why your control flow is going in else part.

You need to either correct your statement or your expectations.

Upvotes: 0

Related Questions