Hello! Welcome back to your front-end development course.
In our last lesson, we explored JavaScript's operators, learning how to perform calculations and, most importantly, how to use comparison and logical operators to ask questions that result in a true or false answer.
Today, we'll learn how to make the application act on those answers. This lesson covers how to implement conditional logic using if-else and switch statements to make decisions based on user input or application state. This is the core of creating dynamic user experiences. It’s how you decide whether to show a success message or an error, enable a button, or change a layout based on what the user does or what data is available.
Recap: Asking true/false Questions
Remember how we used operators to create boolean values?
const password = "password123";
const isPasswordValid = password.length >= 8; // This results in `true`
const itemsInCart = 0;
const isCartEmpty = itemsInCart === 0; // This also results in `true`
Now, let's learn how to use these true and false values to control what our code does.
1. The if...else Statement: The Foundation of Decision-Making
The if...else statement is the most fundamental way to make a decision in code. Its logic is very natural: "if a condition is true, do this; else (otherwise), do that."
To get a solid foundation, please start by reading from the MDN Web Docs, the definitive resource for web developers.
Making decisions in your code — conditionals - MDN Web Docs
This article, "Making decisions in your code — conditionals" from MDN, provides a comprehensive overview of conditional logic. We'll start with the most common structure: if...else.
Please read the sections titled "if...else statements" and "else if". Focus on the syntax and how you can chain multiple conditions together.
Now that you've seen the syntax, let's watch a practical example that brings this concept to life in a UI context.
JavaScript for Beginners #7 - If, Else If, Else
This video, "JavaScript for Beginners #7 - If, Else If, Else" by Tech With Tim, demonstrates how to use conditional logic to change the color of text based on user input—a perfect example of dynamic UI.
Watch from 01:05 to 07:07. Pay attention to how if, else, and else if are used to handle different user inputs and produce different visual outcomes.
How it Works
As you've seen, the structure is:
if: Checks a condition. If it'strue, the code inside its curly braces{}runs, and the rest of the statement is skipped.else if: If the firstifwasfalse, JavaScript checks theelse ifcondition. You can have as manyelse ifblocks as you need. The first one that evaluates totruewill run its code, and the rest are skipped.else: This is the fallback. If none of theiforelse ifconditions weretrue, theelseblock runs.
This creates a clear decision-making path. Let's look at a common UI scenario: displaying the number of notifications.
const notificationCount = 5;
if (notificationCount === 0) {
console.log("Display: You have no new notifications.");
} else if (notificationCount === 1) {
console.log("Display: You have 1 new notification.");
} else {
// The 'else' block handles any other number (2, 3, 4, etc.)
console.log(`Display: You have ${notificationCount} new notifications.`);
}
// Output: Display: You have 5 new notifications.
This logic ensures the message is always grammatically correct and relevant, a small but important detail in user experience design.
2. The switch Statement: For Handling Defined States
Sometimes, you have a single value that can be one of several predefined options. For example, a user's role could be 'admin', 'editor', or 'viewer', or the status of a data request could be 'loading', 'success', or 'error'.
While you could use a long if...else if...else chain, a switch statement is often cleaner and more readable for this specific job.
This next video explains what switch statements are and, more importantly, discusses the design pattern of using them to manage application states.
JavaScript Switch Statements - When to use switch over if/else?
In "JavaScript Switch Statements" by Ijemma Onwuzulike, you'll learn about the switch statement and a key use case: managing different states in your application.
Watch from 00:00 to 05:59. Focus on: The basic syntax of switch, case, break, and default. The concept of using switch to handle different 'states'. The importance of the break keyword to prevent 'fall-through'.
switch for State Management
The idea of "state" is central to modern UI development. A state is a snapshot of your application's condition at a moment in time. As a designer, you create different mockups for these states: the loading screen, the empty state, the success screen, the error page. The switch statement is an excellent tool for implementing the logic that displays the correct UI for each state.
Here is the syntax in action:
const dataFetchStatus = 'loading'; // This could change to 'success' or 'error'
switch (dataFetchStatus) {
case 'loading':
console.log("UI Action: Show a loading spinner.");
break; // The 'break' is crucial! It stops execution here.
case 'success':
console.log("UI Action: Display the fetched data.");
break;
case 'error':
console.log("UI Action: Show an error message and a 'retry' button.");
break;
default:
// A fallback for any unexpected status
console.log("UI Action: Show a generic message.");
}
// Output: UI Action: Show a loading spinner.
Without break, the code would "fall through" and execute the code in the following cases, leading to bugs.
if-else vs. switch
- Use
if-elsewhen you have complex conditions involving different variables or ranges (e.g.,score > 90,password.length >= 8 && hasNumber). - Use
switchwhen you are checking a single variable against a list of specific, discrete values (e.g.,status === 'loading',day === 'Monday'). It often makes your code more readable in these scenarios.
3. Your Turn: Practice with Conditionals
Now it's time to put this into practice. The MDN article you read earlier has interactive exercises that are perfect for this.
- Calendar Logic: Go back to the MDN article and complete the exercise under the section "Implementing a basic calendar". This task requires you to use an
if...else ifchain to determine the number of days in a month—a classic conditional logic problem. - Theme Switcher: Next, complete the exercise under "Adding more color choices". This challenges you to use a
switchstatement to build a theme selector, a task that directly relates to your work in UI design.
Making decisions in your code — conditionals - MDN Web Docs
Let's return to the MDN article to complete two hands-on exercises.
Find and complete the interactive exercises under the headings "Implementing a basic calendar" and "Adding more color choices". You can edit the code directly on the page and see the results live.
4. A Concise Alternative: The Ternary Operator
For very simple if...else choices, there is a compact syntax called the ternary operator. It's often used for assigning one of two values to a variable based on a condition. You will see it frequently in front-end code, so it's good to be able to recognize it.
The syntax is condition ? valueIfTrue : valueIfFalse;
Here’s a simple if...else statement:
const isLoggedIn = false;
let buttonText;
if (isLoggedIn) {
buttonText = "Log Out";
} else {
buttonText = "Log In";
}
console.log(buttonText); // "Log In"
And here is the exact same logic using a ternary operator:
const isLoggedIn = false;
const buttonText = isLoggedIn ? "Log Out" : "Log In";
console.log(buttonText); // "Log In"
It's clean and concise for simple cases, but for anything more complex, a full if...else statement is more readable and should be preferred.
Conclusion
Great job! You've now mastered the fundamental skill of controlling your program's flow. This is where code starts to feel powerful, moving beyond static instructions to dynamic, responsive logic.
Key Takeaways:
if...else if...elseis your versatile tool for handling decisions, from simple choices to complex, multi-part conditions.switchis a clean and readable alternative for checking a single variable against a list of predefined, exact values. It's particularly well-suited for managing application states (e.g.,loading,success,error).- The ternary operator (
? :) is a useful shorthand for simple, two-path conditional assignments. - Always remember the
breakstatement in yourswitchcases to prevent unintended "fall-through" behavior.
In our next lesson, we will learn about functions. Functions allow us to package up reusable pieces of logic—like the conditional blocks we wrote today—into named, callable units. This is the key to organizing your code, avoiding repetition, and building complex applications in a structured way.
Can't find a good explanation? Sign up and we'll make it for you
Sign up