I want a ternary operator in JavaScript to return nothing if the statment is false I have tried this:
1 == 1 ? alert('YES') : '';
But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.
I want a ternary operator in JavaScript to return nothing if the statment is false I have tried this:
1 == 1 ? alert('YES') : '';
But I want to know if this is the right way to make a statments "DO NOTHING" depending on the condition.
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 ==
.
If you really want to do it, &&
will be one way.
1 == 1 && alert('ALERTED');
1 == 2 && alert('NOT ALERTED');
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.