Shany  Jenkins

Shany Jenkins

1626170460

JavaScript Operators — What is the Ternary Operator and How Does it Work?

JavaScript includes one operator that features three operands. This is called the ternary operator.

This post continues the series on JavaScript operators, wherein we had previously covered the unary and binary operators. The ternary operator is sometimes called a conditional operator and is used often for a shortened version of the if...else statement. Using the ternary operator can help to condense code, although it is sometimes criticized for contributing to less transparent and readable code compared to the if...else statement.

Constructing a Ternary Operators

The ternary operator, as the name implies, requires three operands. The ternary operator statement includes a condition, which is evaluated. The conditional statement is followed by a question mark. Upon evaluation, the operator will execute the code before the colon if the result of the condition is true and the code after the colon if the result of the condition is false.

condition (truthy or falsy) ? `code to execute if truthy` : `code to execute if falsy`;

#javascript

JavaScript Operators — What is the Ternary Operator and How Does it Work?