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)
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.
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.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With