Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Ternary operator – JavaScript

Length: 10 minutes

Details

The ternary operator is essentially a compact way of writing an if…else statement. It consists of a condition, a question mark, an expression, a colon, and a second expression. The first expression is evaluated if the condition is true, while the second expression is evaluated if the condition is false.

True condition

let ternary = true ? 'The condition is true' : 'The condition is false';

In the example above, the first expression will be evaluated since the condition is true. Therefore, the value of the variable will be set to the ‘The condition is true’.

False condition

let ternary = false ? 'The condition is true' : 'The condition is false';

In the example above, the second expression will be evaluated since the condition is false. Therefore, the value of the variable will be set to the ‘The condition is false’.

Demo

Exercises

Try the following statements in the console:

true ? 'The condition is true' : 'The condition is false';
false ? 'The condition is true' : 'The condition is false';

The first statement’s output will be “The condition is true”. The second statement’s output will be “The condition is false”.

Reference

Conditional (ternary) operator on MDN

Back to: JavaScript Reference > JS Conditional Statements