Home > other >  "Do nothings" as statment in Javascript Condition
"Do nothings" as statment in Javascript Condition

Time:11-26

I want a ternary operator in JavaScript to return nothing if the statment is false I have tried this:

 1 == 1 ? alert('YES') : '';
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.

CodePudding user response:

No, use if.

if (1 == 1) {
  alert('YES');
}

Don't abuse the conditional operator as a replacement for if/else - it's confusing to read. I'd also recommend always using === instead of ==.

CodePudding user response:

If you really want to do it, && will be one way.

1 == 1 && alert('ALERTED');
1 == 2 && alert('NOT ALERTED');
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

It is single statement. A condition after an AND operator is only run if the first is true. So it is like an if statement.

CodePudding user response:

did you try a single line if statement without brackets?

if(1 == 1) alert('Yes');
  • Related