You will be able to explain and write JavaScript control flow using conditionals, loops, and try/catch/finally to decide what code runs, how many times it runs, and how errors are handled.
What it is
Control flow is the order in which JavaScript statements execute. By default, code runs from top to bottom. Conditionals such as if and switch choose one branch. Loops such as for and while repeat a block. Exceptions use throw, catch, and finally to jump out of normal flow when something goes wrong. Related terms include branch, iteration, loop body, exception, and cleanup.
Why it matters
- It lets programs respond to different inputs without duplicating code.
- It prevents invalid states by checking conditions before acting.
- It makes repetitive work manageable, such as processing arrays.
- It keeps error handling separate from normal logic.
- It helps you reason about execution order, especially with
return,break, andfinally.
Syntax or steps
The smallest useful control-flow pattern combines a decision, a loop, and error handling:
if (condition) {
// run when condition is true
} else {
// run when condition is false
}
for (let i = 0; i < count; i++) {
// repeat count times
}
try {
// code that may throw
} catch (e) {
// handle the error
} finally {
// cleanup that always runs
}
Read it as: test a condition, repeat work while needed, and protect risky code with a fallback path.
Example
function processOrder(order) {
let total = 0;
try {
if (!order || !Array.isArray(order.items)) {
throw new Error("Missing order items");
}
for (const item of order.items) {
if (item.price < 0) {
throw new Error("Negative price");
}
total += item.price;
}
return total;
} catch (e) {
console.error(e.message);
return 0;
} finally {
console.log("Processing finished");
}
}
console.log(processOrder({ items: [{ price: 10 }, { price: 5 }] }));
console.log(processOrder(null));
Part by part:
processOrderstarts withtotal = 0, then enterstry.- The
ifchecks whether the input has an array of items. If not,throwjumps tocatch. - The
forloop visits each item. If a price is negative, it throws another error. - If no error occurs,
return totalis reached, butfinallyruns first. - The first call prints
Processing finished, then15. The second call prints the error message, thenProcessing finished, then0.
Common mistakes
- Forgetting braces. A single-statement
ifcan become misleading when edited. Always use braces for clarity. - Returning from
finally. Areturninsidefinallycan hide the original result or error. Keepfinallyfor cleanup only. - Creating infinite loops. If the loop condition never becomes false, the program freezes. Make sure the loop variable changes each pass.
- Using exceptions for normal flow. Expected cases, such as an empty cart, should usually use conditionals, not
throw.
When to use it
Control flow is not one tool; it is a set of tools. Choose the smallest construct that matches the problem.
| Construct | Use when | Prefer alternative when |
|---|---|---|
if / else | There are two or three clear branches. | Many discrete values match one variable; use switch. |
for / while | You need to repeat work. | You only need to transform an array; use map or forEach. |
try / catch | An operation may fail unexpectedly. | The failure is a normal business rule; use validation and if. |
finally | Cleanup must happen after success or failure. | Cleanup is only needed on success; put it after the risky call. |
Practice
Guided exercise: Write a function that loops through the numbers 1 to 5, skips 3, and returns the sum. Expected output: 12.
Challenge: Modify processOrder so it also rejects items without a price property. Hint: use if (typeof item.price !== "number") inside the loop.
Quick check
Question: Does finally run if the try block returns a value?
Answer: Yes. JavaScript runs finally before the function actually returns.
Summary
Control flow shapes a program by deciding which statements run, how often they run, and what happens when something fails. In JavaScript, conditionals branch, loops repeat, and try/catch/finally handles exceptional paths while keeping cleanup predictable.