Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient alternative to if (a>b) in javascript for checking a variable range

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?

like image 492
tim Avatar asked Feb 16 '23 23:02

tim


2 Answers

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
like image 78
Paul Avatar answered Feb 18 '23 18:02

Paul


You can use ternary operators

var blah;

blah = a > 10 ? 'large' : (a > 5 ? 'medium' : 'small' ) ;
like image 42
Sushanth -- Avatar answered Feb 18 '23 17:02

Sushanth --