Home Basics JavaScript ternary operator

JavaScript ternary operator

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is true followed by a colon (:), and finally the expression to execute if the condition is false

This operator is often used as an alternative to theif...else statement.

Syntax

condition ? expressionTrue : expressionFalse

Parameters

condition
An expression whose value is used as a condition.
expressionTrue
An expression which is executed if the condition evaluates to a true value (one which equals or can be converted to true).
expressionFalse
An expression which is executed if the condition is false (that is, has a value which can be converted to false).

Besides false, possible false expressions are: nullNaN0, the empty string (""), and undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression expressionFalse.

Examples

 

let passMark = 49;
let message;

passMark >= 50 ? (message = 'You passed the test.') : (message = 'You failed the test.');

console.log(message);

Output:

You failed the test

Using multiple JavaScript ternary operators example

The following example shows how to use two ternary operators in the same expression

 

let speed = 70;
let message = speed >= 120 ? 'Too Fast' : speed >= 60 ? 'Fast' : 'OK';

console.log(message);

 

You may also like