How to Use The JavaScript Ternary Operator With Examples

JavaScript Ternary Operator

The JavaScript ternary operator also called the conditional operator or Question mark operator is an operator that takes three operands. It is the only JavaScript operator that takes three operands.

It consists of a condition followed by a question mark (?), then an expression to execute if the condition is true followed by a colon (:). Finally, the expression to execute if the condition is false comes thereafter. This operator is frequently used as a shortcut for the if statement.

The following is the syntax of the JavaScript ternary operator:

condition ? value if true : value if false

Let’s take a look at a simple example:

Using JavaScript Ternary Operator Conditional Chains

The ternary operator is right-associative, which means it can be “chained”. This is similar to an if … else chain as compared below:

The above is equivalent to this:

Ref: https://tc39.es/ecma262/#sec-conditional-operator