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)