DEV Community

Cover image for ๐Ÿง  10-Day Challenge: Day-3 Conditional Statements
Smriti Singh
Smriti Singh

Posted on

๐Ÿง  10-Day Challenge: Day-3 Conditional Statements

๐Ÿ“… 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!");
}
Enter fullscreen mode Exit fullscreen mode

โœ… 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.");
}
Enter fullscreen mode Exit fullscreen mode

โœ… 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");
}
Enter fullscreen mode Exit fullscreen mode

โœ… 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);
Enter fullscreen mode Exit fullscreen mode

โœ… 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.");
}
Enter fullscreen mode Exit fullscreen mode

Using Ternary Operator

console.log(age >= 18 ? "You can vote!" : "You are too young to vote.");

Enter fullscreen mode Exit fullscreen mode

โ“ Interview Questions (Day 3 Topics)

  1. Whatโ€™s the difference between if, else if, and else?
  2. When should you use a ternary operator over an if...else block?
  3. How does JavaScript evaluate multiple conditions in a chain?
  4. What happens if no condition in an if...else if chain is true?
  5. Whatโ€™s the output of:
let age = 18;
console.log(age >= 18 ? "Yes" : "No");
Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰ 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)