I hope the title is not too generic nor misleading.
var blah;
if(a > 10) blah = 'large';
if(a <= 10 && a > 5) blah = 'medium';
if(a <= 5 && a >= 0) blah = 'small';
isn't there a more elegant and concise way to implement a range-check?
Yes, use else
clauses:
var blah;
if(a > 10){
blah = 'large';
}else if(a > 5){
blah = 'medium';
}else if(a >= 0){
blah = 'small';
}
Since you are doing a simple assignment in each statement it could also be elegant to use a ternary expression, although many would argue that this is less readable:
var blah =
a > 10 ? 'large' :
a > 5 ? 'medium' :
a >= 0 ? 'small' :
undefined; // May want to choose a better default value for a < 0
You can use ternary operators
var blah;
blah = a > 10 ? 'large' : (a > 5 ? 'medium' : 'small' ) ;
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