DEV Community

Cover image for The JavaScript Ternary Operator β€” Your New Best Friend for Clean Code πŸš€
OneDev
OneDev

Posted on

The JavaScript Ternary Operator β€” Your New Best Friend for Clean Code πŸš€

If you’re still writing simple if...else blocks like it’s 1999, let me introduce you to a little gem: the ternary operator. It’s the fastest way to make your code cleaner, shorter, and yesβ€”way cooler.


🧠 What is it?

Think of the ternary operator as a quick decision maker:

condition ? doThisIfTrue : doThatIfFalse;
Enter fullscreen mode Exit fullscreen mode

It’s like asking your code: β€œHey, is this true? If yes, do this. If no, do that.”

✨ Why should you care?

Because it saves you from writing bulky code like this:

let message;
if (isLoggedIn) {
  message = "Welcome back!";
} else {
  message = "Please log in.";
}
Enter fullscreen mode Exit fullscreen mode

Instead, just do this:

const message = isLoggedIn ? "Welcome back!" : "Please log in.";
Enter fullscreen mode Exit fullscreen mode

Boom! One line, same result.

πŸ”₯ Real talk β€” when to use it?

  • βœ… Great for quick checks and simple assignments.
  • βœ… Perfect inside JSX for React components.
  • ⚠️ Avoid when logic gets complicated β€” readability > brevity!

πŸ’‘ Pro tip: Keep it simple!

Nested ternaries are tempting but can turn your code into spaghetti:

const status = score > 90 ? "A" : score > 75 ? "B" : "C";
Enter fullscreen mode Exit fullscreen mode

Use with care and add comments if needed.

βœ… Challenge

Replace your next simple if...else with a ternary. See how much cleaner your code looks!
Got a favorite ternary trick? Drop it below and let’s share the love πŸ’™πŸ‘‡

Top comments (0)