📅 Day 3: Conditional Statements
Welcome to Day 3 of our JavaScript Learning Challenge! 🧠
Today, we’re stepping into the world of decisions in JavaScript — using conditional statements to control the flow of your program.
🤔 What Are Conditional Statements?
Conditional statements allow you to run different blocks of code depending on whether certain conditions are true or false.
Think of it like this:
“If it’s raining, take an umbrella. Else, wear sunglasses.
✅ if Statement
The most basic decision-making syntax.
let age = 18;
if (age >= 18) {
console.log("You are eligible to vote!");
}
✅ if...else Statement
Use this when you need two different paths.
let age = 16;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You are not eligible to vote yet.");
}
✅ else if Statement
For checking multiple conditions in sequence.
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: D");
}
✅ Ternary Operator (Shorthand for if...else)
A more compact syntax for simple decisions.
let age = 20;
let message = age >= 18 ? "You Can Drive" : "You Cannot Drive!";
console.log(message);
✅ Example: Voting Eligibility Checker
Write a JavaScript program that checks whether a person is eligible to vote based on their age.
🧪 Requirements:
If age is 18 or above, print "You can vote!"
If age is below 18, print "You are too young to vote."
🧠 Example Solution:
let age = prompt("Enter your age:");
age = Number(age);
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You are too young to vote.");
}
Using Ternary Operator
console.log(age >= 18 ? "You can vote!" : "You are too young to vote.");
❓ Interview Questions (Day 3 Topics)
- What’s the difference between if, else if, and else?
- When should you use a ternary operator over an if...else block?
- How does JavaScript evaluate multiple conditions in a chain?
- What happens if no condition in an if...else if chain is true?
- What’s the output of:
let age = 18;
console.log(age >= 18 ? "Yes" : "No");
🎉 Awesome! You’ve now mastered conditional logic in JavaScript.
Tomorrow in Day 4, we’ll explore Loops — the magic behind repetition and iteration in code.
Top comments (0)