Open Playground
JS TutorialLesson #19

The JavaScript Ternary Operator

The conditional operator is a shorthand for writing conditional if...else statements.

Example

Example Code

javascript
Try it Yourself
let text = (age
 Share

## Description

The conditional operator is a shorthand for writing conditional `if...else` statements.

It is called a ternary operator because it takes three operands.

### Syntax

javascript (condition) ? expression1 : expression2 ```

Parameters

ParameterDescription
conditionRequired. The condition to be tested. An expression that evaluates to true or false.
?Required. The operator separating the condition from the expressions.
expression1Required. The value to return if the condition is true.
:Required. The operator separating the expressions.
expression2Required. The value to return if the condition is false.
The conditional (ternary) operator is the only JavaScript > operator that takes three operands.

Browser Support

() ? x : y is an ES1 feature (JavaScript 1997).

It is fully supported in all browsers:

ChromeIEEdgeFirefoxSafariOpera
YesYesYesYesYesYes

★

+1

Sign in to track progress

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let text = (age < 18) ?  "Minor" : "Adult";

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let isMember = true;

let discount = isMember ? 0.2 : 0;

JS Example 3

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
let isMember = false;

let discount = isMember ? 0.2 : 0;

Syntax

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
(condition) ? expression1 : expression2