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:
&& to get the first falsy value or, if there isn't any, the last truly one.|| to get the first truly value or, if there isn't any, the last falsy one.Therefore:
If b is falsy
Then, b<=200 && b is falsy, so b<=200 && b || c gives c
If b is truly
If b<=200
Then, b<=200 && b gives b, which is truly, so b<=200 && b || c gives b too.
If b>200
Then, b<=200 && b gives false, which is falsy, so b<=200 && b || c gives c.
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)
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