The Ternary Operator

Sam Hall
3 min readSep 28, 2021

--

A handy shortcut alternative to the if statement in JavaScript.

Image courtesy of javatpoint.com

Last week I discussed conditional statements in JavaScript, their syntax and how to implement them in your code. Conditional statements in JavaScript using keywords like if, else, and else if can be expressed instead using the ternary operator (or “conditional operator”). The ternary operator makes your code simpler, shorter and more legible in a mass of other code performing other tasks.

Who doesn’t want code that’s short, sweet and to the point?

Alright I’m already getting off track.

Let’s look at the example from last week, wherein we wrote a conditional if/else statement to determine if a person was athletic enough to qualify for a particular sport:

If the condition (inside the parentheses following the keyword if) is met, the code block following it will run. Conversely, if the condition is not met (if the variable “athletic” is not truthy), the code block following the else key word will run instead. Pretty neat huh? But so much code just for this one function? Nah. Lets clean it up!

Instead we can write a function “whichTeam” to determine if the condition “isAthletic” is met. Syntactically, the condition occurs before a question mark (?), followed by a first block of code (the expression that will execute if the condition renders a truthy value. The first block is followed by a colon (:) and then a second block of code (the expression that will execute if the condition renders a falsey value). As you can see by the following console.logs, the function produces the same results as the much wordier, and therefore more prone-to-bugs, if/else statement.

Further Reading

All examples created using repl.it.

--

--

Sam Hall
Sam Hall

Written by Sam Hall

Full stack developer and stand-up comic.

No responses yet