Curriculum
Module 04 // Core JavaScript
Control Flow
Module Objective
if/else, switch, loops, break/continue, try/catch/finally, throw
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Break vs Continue
for (let i = 0; i < 5; i++) {
if (i === 2) continue; // Skip 2
if (i === 4) break; // Stop at 4
console.log(i);
}
// Output: 0, 1, 3💡 `continue` skips the rest of the current iteration. `break` exits the entire loop immediately.
// Example 2
// 2. For...of vs For...in
const fruits = ['apple', 'banana'];
for (const fruit of fruits) {
console.log(fruit); // 'apple', 'banana' (Values)
}
for (const index in fruits) {
console.log(index); // '0', '1' (Keys/Indices)
}💡 `for...of` is for **values** in iterable objects (Arrays, Strings). `for...in` is for **keys** (property names) in objects.
// Example 3
// 3. Try...Catch...Finally
try {
console.log("Starting...");
throw new Error("Oops!");
} catch (error) {
console.log("Caught:", error.message);
} finally {
console.log("Cleaning up...");
}
// Output: Starting..., Caught: Oops!, Cleaning up...💡 `finally` always runs, whether an error was thrown or not. Great for closing database connections or stopping loading spinners.
Engine & Memory Architecture
Control Flow in Memory
1. The Call Stack:
- Conditional branches don't create new Stack frames, but Loops do maintain state (like
i) in the current frame. - Errors capture the current Stack trace, allowing you to see exactly where the failure occurred.
2. CPU Branch Prediction:
- Modern CPUs try to "guess" which way an
ifstatement will go to speed up execution. - Complex nested loops can be heavy on the CPU as it recalculates the condition and jumps back to the start of the block.
3. Scope:
- Blocks
{}insideiforforcreate their own Lexical Environments forletandconst.