JAVASCRIPT TERNARY OPERATORS

Jerry Simba
2 min readJun 19, 2022

--

Using ternary operators is the best way to write short and precise code when using if/else statements. In short, it is used to avoid writing lengthy code when using these conditionals.

Ternary operators execute the exact same purpose of the conditional, with just a shorter and more concise structure.

conditional ? (if condition is true) : (if condition is false)

example 1

For example, examine the following code…

output: yellow

To use the ternary operator, first provide a conditional statement on the left side of the ?. Then, between the ? and : write the code that would run if the condition is true and on the right-hand side of the : write the code that would run if the condition is false. For example, you can rewrite the example code above as:

output = yellow

This code not only replaces the conditional but also handles the variable assignment for color.

example 2

output = herbivore;

The code can be simplified by the ternary series below:

output = herbivore;

--

--

Jerry Simba
Jerry Simba

Written by Jerry Simba

Data. Data Journalism, Data Analyst , Data Engineer. I live in Nairobi, Kenya.

No responses yet