JavaScript Conditional(Ternary) Operator

Control flow is one of the essential concepts in programming languages. Besides using if and else, JavaScript offers a concise syntax: the conditional (ternary) operator.

As the name suggests, it consists of three parts: “condition, success flow, and failure flow.” When a conditional expression is set. If the condition is true, the success flow is executed; otherwise, the failure flow is executed. The concept is similar to if and else, but the syntax of the conditional operator is more concise and can be completed in one line, making it a very popular and commonly used syntax.

// Traditional syntax
const age = 18;
let result = '';
if (age >= 18) {
result = 'Adult';
} else {
result = 'Minor';
}
// Condition ? Success flow : Failure flow
const age = 18;
const result = age >= 18 ? 'Adult' : 'Minor';

Using the conditional operator can significantly reduce the length of the code, similar to a mini version of if else.

Common Mistakes

Besides simple control flow, it is best not to use the conditional operator in overly complex situations, as it can make the code difficult to read; brevity does not always mean readability.

// Traditional syntax
const wallet = 100;
let result = '';
if (wallet >= 100) {
result = 'Buy a hamburger';
} else if (wallet >= 50) {
result = 'Buy a coffee';
} else {
result = 'Can only drink water';
}
// Conditional operator
const wallet = 100;
const result = wallet >= 100 ? 'Buy a hamburger' : wallet >= 50 ? 'Buy a coffee' : 'Can only drink water';

References