Using the JavaScript Ternary Operator

The ternary operator (sometime called conditional operator) is one of the most underused features of JavaScript, mainly due to a lot of people find it confusing on first glance.

Why

Practically everyone uses conditional formatting:

if(condition) {
  `do something`
} else {
  `do something else`
}

How

Although simple enough, one has to type quite a few extra characters. Here is the same logic using the ternary operator:

condition ? `do something` : `do something else`

If `condition` is "truthy", the first instruction is executed, otherwise the second.

Practical examples

Assign a value based on a condition (the ternary operator returns a value):

let colour = width > 100 ? "red" : "blue";

Change an element class list based on state:

var el = document.getElementById("loginButton");
loginInProgress ? el.classList.add("disabled") : el.classList.remove("disabled");

Conclusion

The ternary operator can be a great tool for our JavaScript projects. In most cases, it can be a simple replacement for `if...else` but have in mind this simple but critical difference: the ternary operator is an expression that returns a value whilst `if...else` doesn't.

Next Steps