Javascript Ternary operator with empty else

后端 未结 7 755
梦如初夏
梦如初夏 2020-12-18 13:43

I\'m trying to convert the following if-else to it\'s ternary operator representation in javascript as follows

var x = 2;
if (x === 2) {alert(\"2\");}
else
          


        
7条回答
  •  误落风尘
    2020-12-18 14:02

    I don't like it's either. So you're on the right track looking for alternatives.

    In this case, I would write:

    t===2 && alert("2")
    

    Your idea is valid too, for instance you can do this:

    t===2 ? alert("2") : null
    

    But it's four extra chars.

提交回复
热议问题