Shorthand if/else statement Javascript

前端 未结 7 1426
难免孤独
难免孤独 2020-12-07 16:57

I\'m wondering if there\'s a shorter way to write this:

var x = 1;
if(y != undefined) x = y;

I initially tried x = y || 1, but

相关标签:
7条回答
  • 2020-12-07 17:20

    Other way is using short-circuit:

    x = (typeof y !== 'undefined') && y || 1

    Although I myself think that ternary is more readable.

    0 讨论(0)
提交回复
热议问题