๐
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)