0

I have just learned how to use Javascript ternary conditional operator.

condition ? true : false

The question is i want to use the operator with only false expression.

what i expect

condition : false expression

but above code not work, is there any way ?

Jaeho Lee
  • 151
  • 1
  • 8
  • 1
    You can use `a || b` which will evaluate `b` only if `a` is falsy. See [What does the construct x = x || y mean?](https://stackoverflow.com/q/2802055) | [JavaScript OR (||) variable assignment explanation](https://stackoverflow.com/q/2100758) | [What does “var FOO = FOO || {}” (assign a variable or an empty object to that variable) mean in Javascript?](https://stackoverflow.com/q/6439579) – VLAZ Aug 04 '20 at 05:12
  • 1
    If you want to use this as part of a larger expression, then your “ternary expression” *must* return a value, in either case, so having only a false expression is not possible in that situation…! – deceze Aug 04 '20 at 05:14

3 Answers3

3

Javascript ternary conditional operator for only false expression

This is not possible. You don't even need to know ECMAScript or TypeScript to know that this is not possible, just basic English: the word "ternary" means "composed of three things", so a ternary conditional operator can by definition only have the condition and two consequences.

If it only had a condition and one consequence, it would be a binary conditional operator.

Jörg W Mittag
  • 337,159
  • 71
  • 413
  • 614
2

Please see this Ternary Operator. It clearly says ternary operator has three parts.

  1. Condition
  2. Value if true
  3. value if false

So you cannot do as you asked. Instead you should use simple if and check if condition is false and return false value.

Atif Zia
  • 558
  • 1
  • 8
  • 24
1

condition || expression

can use like

form.isValid || form.submit()

The form's submit method will not be evaluated if the isValid property is falsey.

Adrian Brand
  • 15,308
  • 3
  • 24
  • 46