🔀 Ternary (Conditional) Operator
Last Updated: 11th October 2025
The Ternary Operator is a short way to write if...else conditions in one line.
It checks a condition and returns one of two values based on whether it’s true or false.
Hinglish Tip 🗣: Ye ek shortcut hai “if else” likhne ka — chhoti condition check karke turant result de deta hai.
🧠 Syntax
condition ? value_if_true : value_if_false;
If the condition is true → returns the first value. If false → returns the second value.
⚙️ Example Basic
let age = 18;
let result = age >= 18 ? "You can vote" : "You cannot vote";
console.log(result); // Output: You can vote
⚙️ Example Nested
let marks = 85;
let grade = marks >= 90 ? "A+" : marks >= 75 ? "A" : marks >= 50 ? "B" : "Fail";
console.log(grade); // Output: A
Hinglish Tip 🗣: Nested ternary tab use karo jab multiple conditions ho — jaise grading, status check, etc.Par zyada use mat karo warna code confusing ban jaata hai 😅.
👨💻 Quick Practice
- Check if a number is even or odd using a ternary operator.
- Print "Pass" if marks ≥ 40 else "Fail".
- Create a variable isLoggedIn and print "Logout" if true else "Login".
- Make a nested ternary for temperature: 30 → "Hot", 15–30 → "Warm", else → "Cold".