JS101: Ternary Operator

Let’s talk about the ternary operator! The ternary operator is a conditional operator that can efficiently replace several lines of IF statements, allowing us shorter and tidier code. The ternary operator is the only JavaScript operator that takes 3 operands.

IF statement


Ternary Operator

Let’s break it down:

condition: An expression that’s used as a condition

true: An expression in which the condition evaluates to a truthy value

false : An expression in which the condition is falsy value

Things to keep in mind

Beside false , other examples of falsy expressions are null , NAN , undefined , 0 , or an empty string(“ “). If the condition represents any falsy values, the result will be executed as a false expression.

Wrapping up

Ternary operators are best for readability when they are used for a single expression. If you find yourself writing an IF/ELSE statement, consider using the ternary operator.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store