Ternary Operator — Conditional Breakdown

Need to know more about how to use the ternary operator — great, so do I! First things first… What is a ternary operator? Let’s talk some JavaScript Conditionals!

MDN docs provides us with:

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 truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.

Wonderful! So in other words, this is a one-line shorthand for an if-else statement. Take a look at the syntax below.

Syntax:

condition ? exprIfTrue : exprIfFalse

What would be the parameters for the syntax?

  • exprIfTrue: This is what would happen if the condition expression came back as True.
  • exprIfFalse: This is what would happen if the condition expression came back as False.

Now remember what falsy value types there are:

1. false
2. null
3. NaN - (not a number)
4. 0
5. undefined
6. (" ") - even an empty string

Okay, so now we know the syntax… let’s do another explanation:

You write x ? y : z, where x, y, and z are all JavaScript expressions.

Personally, I am in React mode, so what about as a JSX expression? Below is a JSX example:

const basicDrinkExample = (
<h1>
{ age >= drinkingAge ? 'Buy Drink' : 'Do Teenage Stuff' }
</h1>
);

In the above example, if age is greater than or equal to drinkingAge, then headline will equal <h1>Buy Drink</h1>. Otherwise, basicDrinkExample will equal <h1>Do Teenage Stuff</h1>.

So there you have it folks, a brief explanation on ternary operators — hope this makes it easier for you. When in doubt, practice — practice — practice!

--

--

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