JavaScript Conditionals: If, Else & Switch
Master the art of decision-making in your code by learning how to control its flow with conditional logic.
The 'if' Statement: The Basic Decision
The if
statement is the most basic control structure. It executes a block of code if a specified condition evaluates to true. Think of it as asking a simple "yes or no" question.
Adding an Alternative: 'else'
The else
statement provides a fallback. It executes a block of code if the condition in the preceding if
statement is false. It's the "otherwise" in your logic.
Multiple Choices: 'else if'
When you have more than two possibilities, you can use else if
to chain multiple conditions. Each condition is tested in order until one is found to be true. It's a way to create a ladder of decisions.
The 'switch' Statement: A Clean Alternative
The switch
statement is a clean alternative to a long chain of else if
statements. It evaluates an expression and matches its value against a series of case
clauses to execute the corresponding code block.
Practice Zone
Interactive Test 1: Structure the Logic
Drag the keywords to their logical position in a conditional block.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Complete the Switch
Complete this `switch` statement to handle different user roles.
Rellena los huecos en cada casilla.
let role = 'admin'; (role) { 'admin': console.log('Full access'); ; case 'editor': console.log('Can edit content'); break; : console.log('Guest access'); }
Practice Example: Grading Logic
Write an `if-else if-else` chain to determine a grade based on a score.
Conditionals in Action
Conditionals are the "brains" of an application, allowing it to react dynamically to user input and data. Here are some common real-world examples.
1. Form Validation
Before submitting a form, you almost always use an `if` statement to check if required fields are filled out. This prevents sending incomplete data.
let email = "";
if (email === "") {
showError("Email is required!");
}
Email is required!
2. Displaying User-Specific Content
Websites often show different content based on whether a user is logged in or what their role is (e.g., admin vs. guest).
if (user.isLoggedIn) {
showDashboard();
} else {
showLoginButton();
}
3. Theming and UI Toggles
A `switch` statement is perfect for handling UI changes, like toggling between light, dark, and system themes.
switch (theme) {
case 'dark': setDarkMode(); break;
case 'light': setLightMode(); break;
}
Practical Takeaway: From simple checks to complex application logic, conditionals are fundamental tools for creating responsive, intelligent, and user-friendly web experiences.
JavaScript Conditionals Glossary
- Condition
- An expression that evaluates to either "true" or "false". For example, "age > 18".
- if
- A keyword that begins a conditional block. The code inside only runs if its condition is "true".
- else
- A keyword for a block of code that runs if the preceding "if" (or "else if") condition is "false".
- else if
- Allows you to test a new condition if the previous conditions were not met.
- switch
- A statement that evaluates an expression and executes code corresponding to a matching "case".
- case
- A keyword used inside a "switch" statement to define a specific value to match against.
- break
- A keyword used to exit a "switch" statement. Without it, execution would "fall through" to the next "case".
- default
- A keyword in a "switch" statement that specifies the code to run if no "case" matches.