Ternary Conditional Operator Typescript

The Typescript conditional operator is a Ternary Operator, which takes three operands. The first operand is a condition to evaluate. It is followed by a question mark (?), then an expression (expression1). It is then followed by a colon (:) and second expression (expression2). If the condition is true, then expression1 executes & if the condition is false, then expression2 executes. The conditional operator is a shorthand way to write an If else statement.

The syntax is as follows

Syntax

Where
condition: is a boolean expression, which returns true false.
expression1: executes if the condition is true.
expression2: executes if the condition is false.

Example

Ternary Operator is an operator which takes three operand. The conditional operator is the only one Ternary Operator in Typescript. If the operator requires two operand, then it is a binary operator. If it requires only one operator, then it is a Unary Operator

Conditional operator Example

Conditional Operator is a shortcut to If condition. The above code is same as the following if statement.

Multiple Conditions in Ternary Operator

We can also add Multiple Conditions or nested conditions to a Ternary Operator.

The check function is equivalent to the following if else if else statement

Reference

  1. Expressions & Operators
  2. Precedence & Associativity

Read More

  1. Complete Typescript Tutorial
  2. Typescript Operators
  3. Arithmetic Operators
  4. Unary plus / Unary minus Operators
  5. Increment/Decrement Operators
  6. Comparison / Relational Operators
  7. Equality Operator / Strict Equality Operators
  8. Ternary Conditional Operators
  9. Logical Operators
  10. Bitwise Operators
  11. Assignment Operators
  12. Nullish coalescing operator
  13. Comma Operator in Typescript
  14. Operator Precedence

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top