Excellent! Now we'll put those comparison and logical operators to use by learning Conditionals, which allow your program to make decisions.
🚦 Conditionals: Controlling the Flow
Conditionals check if an expression is true or false and execute different blocks of code based on the result.
1. if Statement
The simplest conditional, it executes code only if the condition is true.
const userAge = 17;
if (userAge >= 18) {
// This code only runs if the condition is true
console.log("You are old enough to vote.");
}
// Since 17 is NOT >= 18, the message is not printed.
2. if...else Statement
This runs one block of code if the condition is true, and a separate block if the condition is false.
const temperature = 35; // degrees Celsius
if (temperature > 30) {
console.log("It's a hot day, stay hydrated! ☀️");
} else {
// This code runs if the condition (temperature > 30) is false
console.log("The temperature is mild. 🌡️");
}
// Output: "It's a hot day, stay hydrated! ☀️"
3. if...else if...else Statement
Use this to check multiple conditions sequentially. Only the code block corresponding to the first true condition will execute.
const currentScore = 85;
if (currentScore >= 90) {
console.log("Grade: A");
} else if (currentScore >= 80) { // Checked only if the first 'if' was false
console.log("Grade: B");
} else if (currentScore >= 70) { // Checked only if the first two were false
console.log("Grade: C");
} else {
console.log("Grade: F"); // Executes if ALL preceding conditions are false
}
// Output: "Grade: B"
🎯 The switch Statement
The switch statement is useful when you have a single expression to test against multiple potential values. It's often cleaner than a long if-else if chain.
* The code looks for a matching case value.
* break is essential: it stops the execution inside the switch block once a match is found. Without it, the code will continue to execute the next case (known as "fall-through").
* default is optional: it runs if no case matches the expression.
<!-- end list -->
const dayOfWeek = 3; // 1 = Mon, 2 = Tue, 3 = Wed, etc.
switch (dayOfWeek) {
case 1:
console.log("It's Monday.");
break;
case 5:
console.log("It's Friday! 🎉");
break;
case 6:
case 7: // Multiple cases can share the same code
console.log("It's the Weekend!");
break;
default:
console.log("It's a normal weekday.");
}
// Output: "It's a normal weekday." (since 3 wasn't explicitly listed)
🧐 Activity: Combine Operators and Conditionals
Imagine you're building a simple app to check eligibility.
const hasLicense = true;
const isOver21 = true;
// Use the logical AND (&&) operator to combine two conditions
if (hasLicense && isOver21) {
console.log("You can rent a car.");
} else {
console.log("You cannot rent a car at this time.");
}
0 Comments