Now that we've explored the fundamentals of conditional statements, it's time to put your newfound knowledge to the test! Practice problems are the bedrock of understanding. They allow you to actively apply what you've learned, identify areas where you might need more clarity, and solidify your grasp of how if, else if, and else work together to create intelligent programs. Let's dive into some scenarios and craft the logic to solve them.
Problem 1: The Age Checker Imagine you're building a simple program that needs to determine if a user is old enough to access certain content. You'll be given a user's age as input and need to output a message based on that age. Use conditional statements to achieve this.
let userAge = 17;
if (userAge >= 18) {
console.log("You are old enough to access this content.");
} else {
console.log("You are not old enough to access this content.");
}Explanation for Problem 1:
In this case, we have a single condition. If userAge is greater than or equal to 18, we print one message. Otherwise (meaning it's less than 18), we print a different message. This uses a basic if-else structure.
Problem 2: The Grade Evaluator Let's make things a bit more complex. You're given a student's score and need to assign a letter grade. Here's the grading scale:
- 90-100: A
- 80-89: B
- 70-79: C
- 60-69: D
- Below 60: F
Use if, else if, and else to implement this logic.
let studentScore = 85;
if (studentScore >= 90) {
console.log("Grade: A");
} else if (studentScore >= 80) {
console.log("Grade: B");
} else if (studentScore >= 70) {
console.log("Grade: C");
} else if (studentScore >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}Explanation for Problem 2:
This problem elegantly demonstrates the power of else if. The program checks the conditions sequentially. If studentScore is 90 or above, it prints 'A' and stops. If not, it moves to the next else if (is it 80 or above?). This continues until a condition is met or the final else block is executed if none of the preceding conditions were true.