Explain Codes LogoExplain Codes Logo

How do you use the ? : (conditional) operator in JavaScript?

javascript
ternary-operator
javascript-best-practices
code-legibility
Nikita BarsukovbyNikita Barsukov·Nov 23, 2024
TLDR

The JavaScript ? : is a ternary operator for concise if-else logic. It follows condition ? trueCase : falseCase. For instance, assigning winner based on a > b:

let winner = a > b ? 'a wins!' : 'b wins!'; // a and b preparing for a boxing match!

Here, winner will be 'a wins!' if a > b is true, otherwise 'b wins!'.

Grasping this operator helps in crafting cleaner and more efficient code. It's especially useful for inline expressions and can sometimes replace verbose if statements or a series of logical "or" (||) operations.

Expand your toolbox: Shortcuts and gotchas

While the ternary operator is celebrated for its simplicity, its wielders must use it responsibly to maintain code legibility. Let's delve into its creative uses and potential pitfalls:

Quick defaults with ternary

Quickly set default values instead of relying on bigger if-else statements:

let username = inputUsername ? inputUsername : 'guest'; // Or even shorter with '||' username = inputUsername || 'guest'; // Default username is 'guest' - just like in a hotel 😉

Chained and Nested: Use wisely

Chaining ternaries for multiple conditions is possible but should be sparingly done to avoid convoluted code:

let grade = score > 90 ? 'A+' : score > 80 ? 'A' : score > 70 ? 'B' : 'C'; // It's like playing a game of "guess the grade" 🎮

More than assignment: Ternary in action

The ternary operator can also be used to execute functions based on the condition:

isMember ? extendSubscription() : displaySignUpForm(); // Is the member VIP? Extend or show the form!

Right is new Left: Right-associative nature

As an operator that's right-associative, when chaining, it groups from right to left:

let category = age > 60 ? 'Senior' : age > 21 ? 'Adult' : age > 18 ? 'Youth' : 'Teen'; // This age-checker is NOT Ageist! 😇

Advanced cases: Ternary-expert in no time

In the path to mastering the ternary operator, here are few advanced usage scenarios:

Cutting redundancy

Don't allow repetitions within the trueCase and falseCase blocks, time to refactor:

// This is a bit repetitive, let's clean it up! let fee = userType === 'child' ? getChildFee() : getAdultFee(); // Cleaner! let fee = getFee(userType);

Ternary and template strings

Combine ternary operator with template literals to make your code expressive:

let greeting = `Have a ${new Date().getHours() > 17 ? 'good evening' : 'good day'}.`; // An inbuilt "goal-oriented" greeting! 🎉

Efficient pairing: Ternary and Arrow functions

In ES6 and beyond, ternary operators blend comfortably with arrow functions:

const canVote = age => age >= 18 ? 'Yes' : 'No'; // "Can I vote?" function to the rescue 😉

Ternary: Not always the best

Knowing when not to use the ternary operator is as crucial as knowing when to use it. If the condition you're evaluating or the expression becomes complex, relying on traditional control structures might be a better choice:

// Complex case, it's better served by an if-else block let mode; if (isRelaxed && hasTime()) { chill(); mode = 'Chill Mode'; } else { prepareToDoList(); mode = 'Work Mode'; } // Remember - All work and no play makes Jack a dull boy! 👨‍💻