...

/

Tip 18: Check Data Quickly with the Ternary Operator

Tip 18: Check Data Quickly with the Ternary Operator

In this tip, you’ll learn how to avoid reassignment with the ternary operator.

We'll cover the following...

The ternary operator

By now, you may have noticed that I love simple code. I’ll always try to get an expression reduced down to the fewest characters I can. I blame a former coworker who reviewed some code I wrote at one of my first jobs.

Node.js
const active = true;
if (active) {
var display = 'bold'
} else {
var display = 'normal'
}
console.log(display)

He took one glance and casually said, “You should just make that a ternary.”

“Of course,” I agreed, not quite sure what he was talking about. After looking it up, I simplified the code to a one-line expression and my code has never been the same.

Node.js
const active = true;
var display = active ? 'bold' : 'normal';
console.log(display);

Why use the ternary operator?

Chances are you’ve worked with ternary operators before. They’re common in most languages, and they allow you to do a ...