Conditional statements allow your JavaScript code to make decisions and execute different actions based on certain conditions. Understanding if, else, and switch statements is essential for controlling the flow of your programs.
1. The if Statement
The if statement executes a block of code only if a specified condition evaluates to true.
let age = 20;
if (age >= 18) {
console.log('You are an adult.');
}
- The condition inside parentheses must evaluate to a boolean.
- Code inside the
{}block runs only when the condition istrue.
2. The else Statement
Use else to execute code when the if condition is false:
let age = 16;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are a minor.');
}
ifhandles the true case;elsehandles the false case.- Ensures that one of the blocks always runs.
3. The else if Statement
For multiple conditions, use else if:
let score = 85;
if (score >= 90) {
console.log('Grade: A');
} else if (score >= 75) {
console.log('Grade: B');
} else if (score >= 60) {
console.log('Grade: C');
} else {
console.log('Grade: F');
}
- Each condition is checked in order.
- The first true condition executes; the rest are ignored.
4. Nested if Statements
You can nest if statements for more complex logic:
let age = 20;
let hasID = true;
if (age >= 18) {
if (hasID) {
console.log('You can enter the club.');
} else {
console.log('ID required.');
}
} else {
console.log('You are too young to enter.');
}
- Useful when conditions depend on multiple factors.
5. The switch Statement
The switch statement is an alternative to multiple if-else statements. It compares a value against multiple cases:
let day = 3;
switch (day) {
case 1:
console.log('Monday');
break;
case 2:
console.log('Tuesday');
break;
case 3:
console.log('Wednesday');
break;
case 4:
console.log('Thursday');
break;
case 5:
console.log('Friday');
break;
default:
console.log('Weekend');
}
breakstops execution of further cases.defaultruns if no case matches.- Ideal for handling discrete values.
6. Best Practices
- Use
===for comparisons to avoid type coercion. - Avoid deeply nested
ifstatements; considerswitchor helper functions. - Always include a
defaultinswitchstatements. - Keep conditions simple and readable.
7. Wrapping Up
Conditional statements are essential for controlling program flow in JavaScript. Mastering if, else, else if, and switch allows you to write code that responds dynamically to different scenarios.
Next Step: Combine conditional statements with logical operators to handle more complex conditions in your code.