Javascript Ternary operator with empty else

跟風遠走 提交于 2019-12-01 01:08:51

Answer to your real question in the comments:

all2.forEach(function (e) {
    e.getAttribute("class") && only.push(e.getAttribute("class"));
});
potatopeelings

Do this :

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

You could replace null by any expression that has no side effect. () is not a valid expression.

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;
}
<input id="txt-val" type="number" />
<button type="button" id="btn-ok">Ok</button>

using a single line if statement is better though

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

In that case you don't need to use Ternary operator. Ternary operator requires a third argument.

condition ? expr1 : expr2

Lokki at Conditional (ternary) Operator

You can use the if statement

if ( t == 2 ) alert(1);

NO, you can't have empty else, better don't use the ternary operator, it requires a third argument. Go with simple if condition.

if(t==2) alert("2");

you have a few options to do this nicely in one line:

option1 - noop function

set a global noop function:

function noop(){}
(t==2)?(alert("1")):(noop());

option2 - && operator

when you use && operater, operands are evaluted only if previos ones where true, so you could miply write:

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

or, for exapmle if you have an arry you want to push to, you could test it is not null before:

arr && arr.push(obj)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!