JavaScript Ternary Operator

Benny Kang
Nov 1, 2021

I have included two ways of writing conditionals ( if/else, switch ) and this Ternary Operator is another one.

Example of Ternary Operator

As you can see above, it does not look familiar but much simpler way of writing conditional. This is basically if age ≥ then display “You can get a driver license. Otherwise, display “You are not eligible to get a driver license”.

Output

Initial variable age is already above 18 so that it displays the first line.

if / else statement

This is basically the same as the above operator and it displays the same result.

Same result

One more useful feature of this operator is that you can even use it in the template literal because it is an expression not a statement.

You cannot use if/else statement inside the template literal.

Inside the template literal

--

--