Shorthand if/else statement Javascript

前端 未结 7 1438
难免孤独
难免孤独 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:07

    Here is a way to do it that works, but may not be best practise for any language really:

    var x,y;
    x='something';
    y=1;
    undefined === y || (x = y);
    

    alternatively

    undefined !== y && (x = y);
    

提交回复
热议问题