2

with an if/else block, else can be omitted when nothing needs doing if the 'if' is not true.

e.g.:

If (A) {
B;
}
// works perfectly well;

When using the ternary operator though, an empty 'else' option throws an error.

e.g.

(A) ? B :  // throws error

(A) ? B // throws error

Putting null as the else option stops the error and seems to work fine but is it safe? Alternatively, what is the correct way to use a ternary statement when there is no need for the 'else' part?

e.g.

(A) ? B : null ; // no error but is it safe or is there a better alternative?
Dave Pritlove
  • 2,601
  • 3
  • 15
  • 14
  • 3
    If there's no `else` then just use a plain old `if` instead of a construct that has an `if` _and_ `else`... – Andreas Apr 29 '20 at 14:56
  • 3
    The ternary conditional operator is not a drop-in replacement for an if/else structure. They're two different things. The ternary conditional operator is meant to evaluate to a value based on a condition. If you're not observing a result of the operator then (1) it doesn't matter if that result is `null` and (2) you're probably using the wrong structure. If you want to perform an operation based on a condition, `if` was designed exactly for that purpose. – David Apr 29 '20 at 14:59
  • Does this answer your question? [Javascript Ternary operator with empty else](https://stackoverflow.com/questions/31960619/javascript-ternary-operator-with-empty-else) – jvilhena Apr 29 '20 at 15:02
  • @jvilhena - it should do but frankly, no as the answers are complicated and overlook the simple answer given by ssb below (which I'd overlooked as a superior alternative). Also, I searched for quite a while and that one didn't feature. I suppose the question is so close that mine may be deleted but I hope not as the simple answer is very pleasing but has passed me by for ages! Thanks. – Dave Pritlove Apr 29 '20 at 15:08
  • @David that makes sense. Thanks. – Dave Pritlove Apr 29 '20 at 15:08

2 Answers2

1

You can use if on a single line if you want as well.

if (a) b;
ssb
  • 1,352
  • 3
  • 18
  • 40
  • Thanks, that's more pleasing than having to specify null. – Dave Pritlove Apr 29 '20 at 15:02
  • 1
    Makes me think of https://www.imperialviolet.org/2014/02/22/applebug.html, I tend to make brackets mandatory personally. – sp00m Apr 29 '20 at 15:02
  • 1
    I'm not necessarily endorsing this as the best stylistically, but it is at the least debatable and in common use. – ssb Apr 29 '20 at 15:03
0

You could take a logical AND && instead.

a && b;

But if you do not need the result of the expression stay with standard if statement.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392