bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/JavaScript/JavaScript Foundations
JavaScript•JavaScript Foundations

The JavaScript Ternary Operator

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind The JavaScript Ternary Operator?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ text = (age < 18) ? "Minor" : "Adult";
3Order

Put the learning moves in the order that makes the concept easiest to apply.

It is called a ternary operator because it takes three operands.
The conditional operator is a shorthand for writing conditional if.
The JavaScript Ternary Operator

Example

let text = (age < 18) ?  "Minor" : "Adult";

Example

let isMember = true;
let discount = isMember ? 0.2 : 0;

Example

let isMember = false;
let discount = isMember ? 0.2 : 0;

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

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

Syntax

(
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

Previous

JavaScript Assignment

Next

JavaScript While Loops