Search code examples
javascriptdefault-valueconditional-operator

Javascript ternary operator: what to put as the false option when none is required?


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?

Solution

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

    if (a) b;