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, ternary
Loops

Repeat actions

for, while, do-while
Jump

Control loop execution

break, continue, return
Error Handling

Manage exceptions

try, catch, finally, throw
Other

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.

StatementSyntaxUse Case
ifif (condition) {...}Single condition
if-elseif (condition) {...} else {...}Two alternatives
if-else if-elseif (c1) {...} else if (c2) {...} else {...}Multiple conditions
nested ifif (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:
JavaScript Editor

๐Ÿ”€ Switch Statements

Multiple Choice Conditions

Switch statements provide a cleaner way to handle multiple discrete values compared to long if-else if chains.

KeywordPurposeImportant
switchStart switch statementEvaluates expression once
caseDefine possible valuesUses strict comparison (===)
breakExit switch blockโš ๏ธ Without break, execution "falls through"
defaultHandle all other casesOptional 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
JavaScript Editor

๐Ÿ”„ 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.

PartPurposeExample
InitializationSet loop counterlet i = 0
ConditionCheck before each iterationi < 10
IncrementUpdate counter after each iterationi++
๐Ÿ’ก For Loop Variations
  • for...in - Iterate over object properties
  • for...of - Iterate over iterable values (ES6)
  • forEach() - Array method for iteration
  • for 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
JavaScript Editor

โณ 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 TypeSyntaxWhen to Use
whilewhile (condition) {...}Check condition before iteration
do-whiledo {...} 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!

JavaScript Editor

โญ๏ธ Break & Continue

Loop Control Statements

Break and continue give you fine-grained control over loop execution, allowing you to exit early or skip iterations.

StatementEffectUse Case
breakExit the entire loop immediatelyFound what you're looking for
continueSkip to next iterationSkip invalid or unwanted items
break labelExit labeled statementExit nested loops
continue labelContinue labeled loopSkip to next iteration of outer loop
๐Ÿ’ก Performance Tips
  • Use break early when target is found
  • Use continue to 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
JavaScript Editor

๐Ÿšจ Error Handling

Try-Catch-Finally

Error handling allows your program to gracefully handle unexpected situations without crashing. It's essential for robust applications.

BlockPurposeWhen Executes
tryCode that might throw errorsAlways, until error occurs
catchHandle thrown errorsOnly if error occurs in try
finallyCleanup codeAlways, regardless of errors
throwCreate custom errorsWhen 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 error
  • TypeError - Wrong type
  • RangeError - Out of range
  • ReferenceError - Undefined variable
  • SyntaxError - Code syntax issues
JavaScript Editor

๐ŸŽฎ 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.

JavaScript Editor
๐Ÿ’ช 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:
breakcontinuereturn
Error:
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