Javascript Conditional Operators: if, ‘?’

Javascript Conditional Operators: if, ‘?’

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.

let age = 18; if (age >= 18) { console.log("You are an adult."); }

📌 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.

let age = 16; if (age >= 18) { console.log("You can vote."); } else { console.log("You cannot vote."); }

📌 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.

let score = 85; if (score >= 90) { console.log("Grade: A"); } else if (score >= 80) { console.log("Grade: B"); } else if (score >= 70) { console.log("Grade: C"); } else { console.log("Grade: F"); }

📌 Output: "Grade: B" (because score = 85)

4️⃣ Ternary Operator (? :)

A shorter way to write if...else statements.

let age = 20; let message = age >= 18 ? "Adult" : "Minor"; console.log(message);

📌 Output: "Adult" (because age = 20)

🔹 Syntax:

condition ? value_if_true : value_if_false

5️⃣ Nested Ternary Operator

Ternary operators can be nested for multiple conditions.

let score = 75; let grade = score >= 90 ? "A" : score >= 80 ? "B" : score >= 70 ? "C" : "F"; console.log(grade);

📌 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. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close