Ternary Operator — Conditional Breakdown

Nicoll Oliver
2 min readJun 9, 2021

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?

  • condition: An expression whose value is used as a condition.
  • 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.

  • When your code is executed, x is evaluated as either “truthy” or “falsy.” If x is truthy, then the entire ternary operator returns y. If x is falsy, then the entire ternary operator returns z

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!

--

--