Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple conditions in an if clause

If I have an if statement that needs to meet these requirements:

if(cave > 0 && training > 0 && mobility > 0 && sleep > 0) 

Is there any way to say that all of them are bigger than zero? Just for more efficient DRY code?

Something like:

if(cave, training, mobility, sleep > 0) 
like image 402
Oliver Klein Avatar asked Aug 06 '15 12:08

Oliver Klein


People also ask

Can you have 3 conditions in an if statement?

If you have to write an IF statement with 3 outcomes, then you only need to use one nested IF function. The first IF statement will handle the first outcome, while the second one will return the second and the third possible outcomes. Note: If you have Office 365 installed, then you can also use the new IFS function.

Can we enter multiple if conditions in an IF formula?

It is possible to nest multiple IF functions within one Excel formula. You can nest up to 7 IF functions to create a complex IF THEN ELSE statement. TIP: If you have Excel 2016, try the new IFS function instead of nesting multiple IF functions.


2 Answers

You could get the lowest value with Math.min, and then you only need one check against the lower bound.

if(Math.min(cave, training, mobility, sleep) > 0) {     //do something } 
like image 93
RilezG Avatar answered Sep 28 '22 05:09

RilezG


You could use an array with .every. This is less DRY, but more verbose:

var isGreaterThanZero = function(val) {     return val > 0; }; if([cave, training, mobility, sleep].every(isGreaterThanZero)) {     // Do Something } 

The reason I like this is that by using an array, it becomes apparent that you're repeating logic for every variable. Naming the callback in an obvious manner helps future readers understand exactly what that check will achieve. And finally, this gives scope for not just numbers, but any check of any type in the future - with any complexity hidden away from the if statement itself.

like image 38
CodingIntrigue Avatar answered Sep 28 '22 07:09

CodingIntrigue