JavaScript Conditional Operators: if
, else
, ?
(Ternary Operator)
Conditional statements allow JavaScript to make decisions based on conditions.
1️⃣ if
Statement
Executes a block of code only if the condition is true
.
📌 If age >= 18
is true
, it prints: "You are an adult."
📌 If age < 18
, nothing happens.
2️⃣ if...else
Statement
Executes one block if true, another block if false.
📌 If age >= 18
, it prints: "You can vote."
📌 If age < 18
, it prints: "You cannot vote."
3️⃣ if...else if...else
Statement
Checks multiple conditions.
📌 Output: "Grade: B"
(because score = 85
)
4️⃣ Ternary Operator (? :
)
A shorter way to write if...else
statements.
📌 Output: "Adult"
(because age = 20
)
🔹 Syntax:
5️⃣ Nested Ternary Operator
Ternary operators can be nested for multiple conditions.
📌 Output: "C"
(because score = 75
)
⚠️ Use nested ternary operators carefully for readability!
🎯 Summary
✅ if
→ Executes code if condition is true
✅ if...else
→ Runs one block if true, another if false
✅ if...else if...else
→ Checks multiple conditions
✅ ? :
→ Shorter way to write if...else
🚀 Now you can handle conditions in JavaScript efficiently! Let me know if you need more details. 😊