support@90-10.dev

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's classes based on state:

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

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.


You can also use nested ternary operators to write complex conditions. However, it is important to use the ternary operator only when it makes the code more readable and simpler. If the condition is too complex, it is better to use the if-else statement.


The ternary operator is a useful tool in JavaScript that allows us to write if-else statements in a concise and readable manner and make our code more efficient and easier to understand.