Node.js Control
Control flow decides what runs next. Node uses the same JavaScript branching and looping rules you would use in any modern JS codebase.
Branching
In backend handlers and CLI tools, guard clauses with early return keep branching shallow and readable. Avoid deeply nested if / else pyramids by handling invalid or missing inputs first:
function describeStatus(status) {
if (!status) return "unknown"; // guard clause for missing input
if (status === "ready") {
return "start";
} else if (status === "wait") {
return "pause";
}
return "stop";
}
Loops
Choose the loop construct that matches what you are iterating over. Unlike array .forEach(), standard for...of loops support break, continue, and await cleanly:
for: Best when you need an explicit numeric index or bounded counter.for...of: Best for arrays, strings, Maps, Sets, and async iterables (for await...offor streams).while: Best when reading paginated APIs or draining a queue until a condition changes.
Switch logic
switch statements use strict equality (===) and work well for dispatching commands or HTTP methods. Always include a break or return at the end of each case to prevent accidental fall-through, or replace simple value-to-value mappings with a plain lookup object or Map:
const command = "build";
switch (command) {
case "build":
console.log("Compiling assets...");
break;
case "test":
console.log("Running test suite...");
break;
default:
console.log(`Unknown command: ${command}`);
}
Practice
Practice writing shallow, predictable control flow:
- Refactor a nested
if / elsevalidation function to use early-return guard clauses. - Iterate over an array with
for...ofand stop early withbreakwhen a target item is found. - Convert a 4-branch
switchmapping strings to labels into aRecord/object lookup with a default fallback.