开发者

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 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜