JavaScript Control Flow
Control flow statements determine the order in which your code executes. They allow you to make decisions, repeat actions, and handle different scenarios in your programs.
🎛️ Control Flow Categories
Conditional
Make decisions in code
if, else, switch, ternaryLoops
Repeat actions
for, while, do-whileJump
Control loop execution
break, continue, returnError Handling
Manage exceptions
try, catch, finally, throwOther
Additional control
label, with🎯 If-Else Statements
Conditional Execution
If-else statements allow your program to make decisions and execute different code blocks based on conditions.
| Statement | Syntax | Use Case |
|---|---|---|
if | if (condition) {...} | Single condition |
if-else | if (condition) {...} else {...} | Two alternatives |
if-else if-else | if (c1) {...} else if (c2) {...} else {...} | Multiple conditions |
nested if | if (c1) { if (c2) {...} } | Complex conditions |
💡 Best Practices
- Use descriptive condition names
- Avoid deeply nested if statements
- Use early returns when possible
- Consider switch for multiple discrete values
🎯 Common Patterns
- Validation - Check input before processing
- Access Control - Check permissions
- Error Handling - Check for errors
- Feature Flags - Enable/disable features
Try If-Else Statements:
🔀 Switch Statements
Multiple Choice Conditions
Switch statements provide a cleaner way to handle multiple discrete values compared to long if-else if chains.
| Keyword | Purpose | Important |
|---|---|---|
switch | Start switch statement | Evaluates expression once |
case | Define possible values | Uses strict comparison (===) |
break | Exit switch block | ⚠️ Without break, execution "falls through" |
default | Handle all other cases | Optional but recommended |
⚠️ Don't Forget Break!
Forgetting break statements causes "fall-through" behavior where multiple cases execute. This is rarely intentional.
🎯 When to Use Switch
- Multiple discrete values - Days, months, roles
- Simple equality checks - No complex conditions
- Readability - Cleaner than long if-else chains
- Intentional fall-through - Grouping cases
🔄 For Loops
Controlled Iteration
For loops are ideal when you know exactly how many times you want to iterate. They provide precise control over the loop counter.
| Part | Purpose | Example |
|---|---|---|
| Initialization | Set loop counter | let i = 0 |
| Condition | Check before each iteration | i < 10 |
| Increment | Update counter after each iteration | i++ |
💡 For Loop Variations
for...in- Iterate over object propertiesfor...of- Iterate over iterable values (ES6)forEach()- Array method for iterationfor await...of- Async iteration (ES2018)
🎯 Common Use Cases
- Array processing - Transform, filter, search
- Number sequences - Count, generate patterns
- DOM manipulation - Process multiple elements
- Data processing - Calculate sums, averages
⏳ While & Do-While Loops
Conditional Iteration
While loops are used when you don't know how many times you need to iterate in advance, but you know the condition to stop.
| Loop Type | Syntax | When to Use |
|---|---|---|
while | while (condition) {...} | Check condition before iteration |
do-while | do {...} while (condition); | Check condition after iteration |
Key Differences:
- while - May execute 0 times
- do-while - Always executes at least once
⚠️ Infinite Loop Danger
Always ensure the loop condition eventually becomes false. Infinite loops can crash your program or browser.
🎯 Common Use Cases
- User input - Wait for valid input
- Game loops - Continue until game over
- Data streams - Process until end
- Retry logic - Retry until success or limit
🔧 Loop Control
Use break to exit early and continue to skip to next iteration. Always have an escape condition!
⏭️ Break & Continue
Loop Control Statements
Break and continue give you fine-grained control over loop execution, allowing you to exit early or skip iterations.
| Statement | Effect | Use Case |
|---|---|---|
break | Exit the entire loop immediately | Found what you're looking for |
continue | Skip to next iteration | Skip invalid or unwanted items |
break label | Exit labeled statement | Exit nested loops |
continue label | Continue labeled loop | Skip to next iteration of outer loop |
💡 Performance Tips
- Use
breakearly when target is found - Use
continueto skip unnecessary processing - Avoid complex nested loops when possible
- Consider array methods for simple iterations
🎯 Practical Examples
- Search - Break when item found
- Validation - Continue if invalid
- Filtering - Skip unwanted elements
- Optimization - Stop when condition met
🚨 Error Handling
Try-Catch-Finally
Error handling allows your program to gracefully handle unexpected situations without crashing. It's essential for robust applications.
| Block | Purpose | When Executes |
|---|---|---|
try | Code that might throw errors | Always, until error occurs |
catch | Handle thrown errors | Only if error occurs in try |
finally | Cleanup code | Always, regardless of errors |
throw | Create custom errors | When you want to signal an error |
⚠️ Error Handling Best Practices
- Only catch errors you can handle
- Always log errors for debugging
- Use specific error types when possible
- Don't swallow errors silently
- Use finally for cleanup (file close, etc.)
🎯 Common Error Types
Error- Generic errorTypeError- Wrong typeRangeError- Out of rangeReferenceError- Undefined variableSyntaxError- Code syntax issues
🎮 Practice: User Management System
Build a complete user management system that uses all the control flow concepts you've learned. This includes validation, loops, error handling, and conditional logic.
💪 Additional Challenges:
- Add email validation with regex
- Implement user update functionality
- Add pagination for user lists
- Create user search with multiple criteria
- Add bulk user operations
- Implement user roles and permissions
📚 Control Flow Summary
Key Takeaways:
- Use if-else for conditional execution
- Use switch for multiple discrete values
- Choose the right loop for your iteration needs
- Always handle errors gracefully
Best Practices:
- Keep conditions simple and readable
- Avoid deeply nested structures
- Use break and continue judiciously
- Always have an escape condition for loops
- Handle errors at the appropriate level
Now that you can control program flow, you're ready to learn about functions - the building blocks of reusable code!
Next: Functions →📋 Control Flow Quick Reference
Conditional:
if (condition) {...}if (c) {...} else {...}switch(value) { case: ... }Loops:
for (let i=0; i<n; i++)while (condition) {...}Jump:
breakcontinuereturnError:
try {...} catch(e) {...}throw new Error("message")Patterns:
- Early return for validation
- Loop until condition met
- Handle errors at boundaries
- Use descriptive condition names
- Avoid magic numbers in conditions
