-2

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.

Chafik
  • 21
  • 3
  • There is no "right way" to make JavaScript do nothing. All of the answers you receive on this question will be opinions. In my opinion, the best way to make JavaScript do nothing is to not write the code in the first place. – Heretic Monkey Nov 25 '21 at 17:56

3 Answers3

1

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 ==.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

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.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
0

did you try a single line if statement without brackets?

if(1 == 1) alert('Yes');
DSMSTHN
  • 40
  • 4