Javascript null coalescing help, how can I incorporate a threshold value? a = b || c but if b > d, choose c
I want to assign a value to a variable in javascript
var a开发者_开发问答 = b || c; //however if b > 200 choose c
Is there a simple way to do this?
var a = (b && b <= 200) ? b : c;
Thanks for any tips or advice. Just trying to write this as cleanly as possible.
var a = b;
if(b == undefined || b > 200){
a = c;
}
You can simplify it even more:
var a = b<=200 && b || c;
Or, more readable,
var a = ( b<=200 && b ) || c;
Explanation:
- You can use
&&
to get the first falsy value or, if there isn't any, the last truly one. - You can use
||
to get the first truly value or, if there isn't any, the last falsy one.
Therefore:
If
b
is falsyThen,
b<=200 && b
is falsy, sob<=200 && b || c
givesc
If
b
is trulyIf
b<=200
Then,
b<=200 && b
givesb
, which is truly, sob<=200 && b || c
givesb
too.If
b>200
Then,
b<=200 && b
givesfalse
, which is falsy, sob<=200 && b || c
givesc
.
Some tests:
100<=200 && 100 || 50 // 100, because 100 is truly and 100<=200
150<=200 && 150 || 50 // 150, because 150 is truly and 150<=200
'150'<=200 && '150' || 50 // '150', because '150' is truly and 150<=200
300<=200 && 300 || 50 // 50, because 300<=200 is false (but 300 is truly)
'abc'<=200 && 'abc' || 50 // 50, because NaN<=200 is false (but 'abc' is truly)
({})<=200 && ({}) || 50 // 50, because NaN<=200 is false (but {} is truly)
false<=200 && false || 50 // 50, because false is falsy (but 0<=200)
null<=200 && null || 50 // 50, because null is falsy (but 0<=200)
''<=200 && '' || 50 // 50, because '' is falsy (but 0<=200)
精彩评论