Effective if (a> b) alternative in javascript for checking a range of variables

I hope the title is not too general or misleading.

var blah; if(a > 10) blah = 'large'; if(a <= 10 && a > 5) blah = 'medium'; if(a <= 5 && a >= 0) blah = 'small'; 

Is there a more elegant and concise way to implement range checking?

+4
source share
4 answers

If you have many time intervals, you can go something like this:

 var ranges = [[10, 'large'], [5, 'medium'], [0, 'small']]; function range(n) { for (var i = 0; i < ranges.length; i++) { if (n > ranges[i][0]) { return ranges[i][1]; } } return 'default value'; } 

This is not so flexible, since you cannot specify < or <= for each case, but if I had many ranges, I could write something like this. The other answers are great, I just thought I'd add this as an idea.

+1
source

Yes, use the else clause:

 var blah; if(a > 10){ blah = 'large'; }else if(a > 5){ blah = 'medium'; }else if(a >= 0){ blah = 'small'; } 

Since you perform a simple assignment in each expression, it can also be elegant to use a three-dimensional expression, although many 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 
+4
source

You can use ternary operators

 var blah; blah = a > 10 ? 'large' : (a > 5 ? 'medium' : 'small' ) ; 
+3
source

If the range is constant, you can use the switch switch and modulo statements. For instance.

 var blah; switch(a-(a % 5)) { case 10: blah = 'large'; break; case 5: blah = 'medium'; break; case 0: blah = 'small'; break; default: blah = 'large'; } 

Of course, it can only be used when the differences between each range are equal.

0
source

Source: https://habr.com/ru/post/1490816/


All Articles