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;
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.";
}
Instead, just do this:
const message = isLoggedIn ? "Welcome back!" : "Please log in.";
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";
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)