Ternary Operator in JavaScript
The ternary operator is a shorthand for writing if...else
statements. It's often used to assign values based on a condition in a single line.
🧠 Syntax
condition ? expressionIfTrue : expressionIfFalse
If the condition is true, it evaluates and returns expressionIfTrue
; otherwise, it returns expressionIfFalse
.
📌 Example 1: Assigning a Value
let age = 20;
let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // "Adult"
📌 Example 2: Inside HTML or JSX
let isLoggedIn = true;
let message = isLoggedIn ? "Welcome!" : "Please log in.";
✅ Why Use the Ternary Operator?
- Shorter and cleaner than
if...else
- Useful for simple decisions and assignments
- Great inside templates and UI rendering
✅ Tip: Avoid nesting ternary operators. It can make code harder to read.