Javascript Ternary operator with empty else

后端 未结 7 740
梦如初夏
梦如初夏 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 13:58

    You putted a lot of useless parentheses, and the best NULL value in js is undefined.

    document.getElementById('btn-ok').onclick = function(){
      var val = document.getElementById('txt-val').value;
      
      val == 2 ? alert(val) : undefined;
    }
    
    

    using a single line if statement is better though

    if(value === 2) alert(value);
    

提交回复
热议问题