Control Flow in JavaScript
Learn how to make decisions and repeat actions in your code.
Prerequisites: Before starting this tutorial, we recommend completing the Variables & Data Types and Operators & Expressions tutorials to understand the concepts used here.
🎯 🧭 Routing the Dinner Rush
Hosts decide where every party sits, kitchens switch menus midday, and chefs handle dietary requests—all by evaluating conditions in seconds. Control flow is the mental playbook that keeps service smooth.
- When have you needed different outcomes based on time, size, or preference?
- How do you personally keep track of multiple "if this, then that" rules?
- Which user actions in your project should branch into unique experiences?
This lesson teaches you to translate real-world branching logic into JavaScript so your apps can react thoughtfully in every situation.
Learning Objectives
By the end of this lesson, you'll be able to:
- ✓ Write readable if/else and else-if ladders for multi-step decisions
- ✓ Choose switch statements when comparing a single value across many cases
- ✓ Use the ternary operator for concise assignments and UI strings
- ✓ Explain Explain truthy/falsy conversions and guard against unexpected coercion
- ✓ Apply Apply logical operators to combine business rules and validations
- ✓ Practice building control-flow challenges that mirror restaurant scenarios
Why This Matters:
Clear objectives keep you focused on crafting logic a teammate (or future you) can follow.
Conditions with If Statements
Conditions allow your code to make decisions based on different situations. Think of them as forks in a road - your code can take different paths depending on certain conditions.
Basic If Statement
The simplest form of a condition. If the condition is true, the code inside the curly braces will run:
⏸️ Checkpoint: Branching Basics
Before moving forward, can you answer these?
- Where would a switch statement simplify the menus or pricing examples above?
- Can you verbalize when a ternary operator improves readability versus hurts it?
- How would you safeguard a condition that depends on user input being truthy?
Tips to Remember:
- Start with plain-language rules, then convert them into code.
- Group related conditions into helper functions to avoid deep nesting.
- Pair console logs with conditional branches while debugging to confirm paths taken.
How confident are you with this concept?
😕 Still confused | 🤔 Getting there | 😊 Got it! | 🎉 Could explain it to a friend!
If-Else Statement
This adds an alternative path. If the condition is true, the first block runs; otherwise, the else block runs:
If-Else If-Else
For multiple conditions, you can chain them together. The code checks each condition in order until one is true:
Real-world analogy: Think of conditions like a restaurant host deciding where to seat guests. If it's a party of 2, seat them at a small table. If it's a party of 4-6, seat them at a medium table. Otherwise, seat them at a large table.
Comparison Operators
These operators compare values and return true or false. They're essential for creating conditions.
Common Mistake
Be careful with == vs ===. The triple equals (===) checks both value AND type, which is usually safer. For example:
5 == "5"is true (same value, different types)5 === "5"is false (different types)
It's generally recommended to use === to avoid unexpected behavior.
Loops
Loops allow you to repeat code multiple times. They're perfect for processing lists of data or doing something a specific number of times.
Here's a brief introduction to loops - we'll cover these in much more detail in the Loops tutorial.
For Loop
The most common loop. It has three parts: initialization, condition, and increment:
While Loop
Repeats as long as a condition is true. Make sure the condition eventually becomes false, or you'll create an infinite loop:
Want to learn more about loops? Check out our dedicated Loops tutorial where we cover all types of loops in JavaScript in much more detail, including for...of, for...in, do...while, and advanced loop techniques.
Switch Statements
Switch statements are useful when you have multiple possible values for a single variable. They're cleaner than writing many if/else statements:
Important Note
Don't forget the break statement after each case! Without it, the code will "fall through" and continue executing the next cases, which is rarely what you want.
Switch Syntax
Switch statements are useful when you have multiple possible values for a single variable. They're cleaner than writing many if/else statements:
Case and Break
Don't forget the break statement after each case! Without it, the code will "fall through" and continue executing the next cases, which is rarely what you want.
Ternary Operator
The ternary operator is a shorthand way to write simple if-else statements. It's perfect for quick conditional assignments and returns.
When to Use Ternary
- ✅ Simple conditional assignments
- ✅ Return statements with two outcomes
- ✅ Template literals with conditional text
- ❌ Complex conditions (use if/else)
- ❌ Multiple outcomes (use if/else if)
- ❌ When readability is crucial
Nested Ternary
While possible, nesting ternary operators can make code hard to read. Use with caution:
❌ Hard to Read
✅ Better Alternative
Truthy and Falsy Values
In JavaScript, values can be converted to booleans automatically in conditional contexts. Understanding truthy and falsy values helps write cleaner conditions.
Falsy Values
These values are considered false when used in conditions:
Truthy Values
Almost everything else is considered true! Here are common examples:
Practical Uses
Understanding truthy/falsy values helps write cleaner code:
Practice Exercises
Interactive Learning: Each exercise includes a "Try It" button that runs the code in your browser's console. Experiment with the code and see how changes affect the output!
Exercise 1: Menu Item Availability
Check if a menu item can be served based on time, availability, and preparation time:
Exercise 2: Customer Discount
Determine the discount using ternary operators and truthy/falsy values:
Exercise 3: Table Assignment
Use switch statements to assign tables based on party size and preferences:
Challenge: Order Validation System
Create a comprehensive order validation system that checks multiple conditions:
Setup
Choose one of these methods to practice:
- Browser Console:
- Open DevTools (F12 or Cmd+Option+I)
- Go to the Console tab
- Type or paste the code directly
- HTML File:
- Create a new file called
practice.htmlor use your existing one - Add this basic structure:
- Create a new file called
Common Issues & Solutions
- Console shows nothing: Make sure you're using console.log() to see results
- Syntax Errors: Check for missing curly braces {} or semicolons ;
- File not updating: Make sure you saved the file and refreshed the browser
- Cannot find console:
- Chrome/Edge: Press F12 or right-click → Inspect
- Firefox: Press F12 or right-click → Inspect Element
- Safari: Enable Developer Tools in Preferences first
Challenge: Black Swan Bistro Menu Filter
Let's put everything together by creating a menu filtering system for our restaurant:
Step 1: Setup Menu Items
Step 2: Create Filter Functions
Hints
- Use array methods like filter()
- Check multiple conditions with && (AND) or || (OR)
- Remember to handle edge cases
Solution
Lesson checkpoint
Test Your Knowledge
Strengthen your understanding of Conditionals by answering the quiz below.
Conditionals Quiz
Test your understanding of Conditionals concepts.
Lesson Complete: What You Learned
Key Takeaways:
- if/else statements let your code choose different paths based on conditions
- switch statements provide a cleaner alternative when comparing one value against many cases
- The ternary operator (condition ? a : b) offers a concise inline conditional expression
- Truthy and falsy values determine how non-boolean values behave in conditions
- Combining conditionals with logical operators enables complex decision-making
- Guard clauses (early returns) keep code flat and readable
Learning Objectives Review:
Look back at what you set out to learn. Can you now:
- ✅ Write if, else if, and else blocks to handle multiple scenarios Check!
- ✅ Use switch statements for clean multi-case comparisons Got it!
- ✅ Apply the ternary operator for concise conditional expressions Can explain it!
- ✅ Identify truthy and falsy values in JavaScript Could teach this!
- ✅ Combine conditionals with logical operators for complex rules Check!
If you can confidently answer "yes" to most of these, you're ready to move on!
Think & Reflect:
Decision Design
- When would you choose a switch statement over a chain of if/else blocks?
- How do guard clauses reduce nesting and improve readability?
Common Pitfalls
- What unexpected results can truthy/falsy values cause if you are not careful?
- How can you avoid accidentally falling through switch cases?
🤔 Real-World Test:
Conditionals power every decision your applications make. From showing different content based on user roles, to validating form inputs before submission, to toggling dark mode based on user preference—if/else logic is everywhere. Games use conditionals to determine win/lose states, and APIs use them to return appropriate responses based on request parameters.
🎯 Looking Ahead:
Now that your programs can make decisions, you're ready to learn about loops. In the next lesson, you'll discover how to repeat actions efficiently—processing arrays of data, iterating through lists, and automating repetitive tasks that would be impractical to write out one by one.
Recommended Next Steps
Related Topics
Explore these related tutorials to expand your knowledge:
Practice Projects
Apply what you've learned with these hands-on projects:
Number Guessing Game
Create an interactive number guessing game that uses conditionals to provide feedback to the player. Practice if statements, comparisons, and logical operators while building a fun game.
Start ProjectAdditional Resources
Deepen your understanding with these helpful resources:
- MDN: Making decisions in your code - Guide to conditional statements in JavaScript
Progress tracking is disabled. Enable it in to track your completed tutorials.
Cookie Settings