JavaScript control flow, errors and async basics
Once you have values, you need to decide what runs and how often, deal with things that go wrong, see what your program is doing, and wait for work that finishes later. This page covers those four skills in order: control flow (conditions and loops), error handling with try/catch/finally, debugging with the console object, and a first look at asynchronous code with callbacks, promises and async/await.
The samples follow an invented shop called OrdersPortal. Running the samples: save each complete sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The output shown under each sample was produced with Node.js 22.23. If you have not read it yet, start with Values, types and operators.
Topics on this page
Section titled βTopics on this pageβ| Topic | What you learn |
|---|---|
| Control flow | if/else, switch, the loops, break and continue. |
| Error handling | throw, try/catch/finally, custom error classes and cause. |
| Console methods | console.log, table, group, count, time and when to use each. |
| Asynchronous code | The event loop in one paragraph, callbacks, promises and async/await. |
Control flow
Section titled βControl flowβControl flow decides which statements run and in what order. JavaScript gives you three kinds of tools:
- Conditionals:
if/else if/elsefor general conditions; the conditional (ternary) operatorcond ? a : bwhen you need a value;switchwhen one value is compared against several fixed cases. - Loops:
for (let i = 0; i < n; i++)when you need an index;for...ofto walk the values of an array, string,Map,Setor any other iterable;for...into walk an objectβs enumerable property names (including inherited ones);whileanddo...whilewhen you loop until a condition changes. - Jumps:
breakleaves the loop orswitch,continueskips to the next iteration, andreturnleaves the function.
switch compares with strict equality (===). Each case falls through to the next one unless you break or return, which is useful for grouping cases and a common source of bugs when forgotten. For arrays, for...of is the usual choice; array methods like filter and map are often clearer still when you are building a new array.
const orders = [ { id: "A-1001", status: "paid", total: 120 }, { id: "A-1002", status: "pending", total: 35 }, { id: "A-1003", status: "cancelled", total: 80 }, { id: "A-1004", status: "shipped", total: 15 },];
function describe(status) { switch (status) { case "paid": case "shipped": return "in progress"; // two cases share one branch case "pending": return "waiting for payment"; default: return "closed"; }}
let revenue = 0;for (const order of orders) { if (order.status === "cancelled") { continue; // skip to the next order } revenue += order.total; const size = order.total >= 100 ? "large" : "small"; console.log(`${order.id}: ${describe(order.status)}, ${size}`);}console.log("revenue:", revenue);
const summary = { paid: 1, pending: 1 };for (const key in summary) { console.log(`${key} -> ${summary[key]}`);}
let attempt = 0;while (attempt < 3) { attempt++; if (attempt === 2) break;}console.log("stopped at attempt", attempt);Output:
A-1001: in progress, largeA-1002: waiting for payment, smallA-1004: in progress, smallrevenue: 170paid -> 1pending -> 1stopped at attempt 2Pitfalls:
for...inon arrays. It yields string indexes, can include inherited properties and is not meant for arrays. Usefor...of.- Missing
breakinswitch. Execution falls through into the next case. Return from each case, or addbreakdeliberately. - Assignment in a condition.
if (status = "paid")assigns and is always truthy. Use===.
Error handling
Section titled βError handlingβWhen something goes wrong, JavaScript throws an exception. Execution stops at that point and jumps to the nearest enclosing catch block; if there is none, the program reports an uncaught error. A try block holds the code that might fail, catch (error) handles the failure, and finally runs afterwards whether or not an error happened, which makes it the place to release resources or reset state. The catch binding is optional since ES2019: catch { ... } is valid when you do not need the error.
You can throw any value, but always throw an Error object or a subclass: it carries a message, a name and a stack trace. Built-in subclasses include TypeError, RangeError and SyntaxError (for example from JSON.parse). Your own subclasses let callers tell failures apart with instanceof. When you catch an error and throw a more meaningful one, pass the original as { cause } (ES2022) so the root cause is not lost.
Catch errors where you can do something useful with them: retry, show a message, or add context. Catching and ignoring an error hides bugs.
class ValidationError extends Error { constructor(message, options) { super(message, options); this.name = "ValidationError"; }}
function parseOrder(json) { let data; try { data = JSON.parse(json); } catch (error) { throw new ValidationError("Order is not valid JSON", { cause: error }); } if (!Number.isInteger(data.qty) || data.qty < 1) { throw new ValidationError(`Invalid quantity: ${data.qty}`); } return data;}
const inputs = ['{"sku":"MUG-01","qty":2}', '{"sku":"MUG-01","qty":0}', "{sku:MUG-01}"];for (const input of inputs) { try { const order = parseOrder(input); console.log("accepted", order.sku, "x", order.qty); } catch (error) { if (error instanceof ValidationError) { console.log(`${error.name}: ${error.message}`); if (error.cause) console.log(" caused by", error.cause.name); } else { throw error; // not ours: let it propagate } } finally { console.log(" checked", input.length, "characters"); }}Output:
accepted MUG-01 x 2 checked 24 charactersValidationError: Invalid quantity: 0 checked 24 charactersValidationError: Order is not valid JSON caused by SyntaxError checked 12 charactersPitfalls:
- Throwing strings.
throw "failed"has no stack trace and noname. Thrownew Error("failed"). - Swallowing errors. An empty
catch {}hides bugs. Handle the errors you expect and rethrow the rest. tryaround async work withoutawait. Atryblock only catches a rejected promise if youawaitit inside the block; see Asynchronous code.
Console methods
Section titled βConsole methodsβThe console object is the built-in debugging toolkit in browsers and Node.js. console.log() prints any values, and objects are shown in an inspectable format rather than as [object Object]. Other methods help organize the output:
console.error()andconsole.warn()mark problems. In Node.js they write to standard error (stderr) instead of standard output, so logs and errors can be redirected separately; in browsers they are styled and filterable.console.table()prints an array of objects as a table.console.group()andconsole.groupEnd()indent related lines.console.count(label)counts how many times a line ran.console.time(label)andconsole.timeEnd(label)measure elapsed time and print something likeload: 12.345ms.console.dir(value, { depth })controls how deep nested objects are printed in Node.js.
For real applications, use a logging library or framework logger with levels, and keep stray console.log calls out of committed code: they clutter output and can leak data such as customer emails into logs.
const lines = [ { sku: "MUG-01", qty: 2, price: 9.5 }, { sku: "TEE-03", qty: 1, price: 18 },];
console.log("order", { id: "A-1001", lines: lines.length });console.table(lines);
console.group("Totals");for (const line of lines) { console.count("line"); console.log(line.sku, line.qty * line.price);}console.groupEnd();
console.dir({ order: { customer: { address: { city: "Lisbon" } } } }, { depth: 0 });Output:
order { id: 'A-1001', lines: 2 }βββββββββββ¬βββββββββββ¬ββββββ¬βββββββββ (index) β sku β qty β price ββββββββββββΌβββββββββββΌββββββΌββββββββ€β 0 β 'MUG-01' β 2 β 9.5 ββ 1 β 'TEE-03' β 1 β 18 ββββββββββββ΄βββββββββββ΄ββββββ΄ββββββββTotals line: 1 MUG-01 19 line: 2 TEE-03 18{ order: [Object] }Pitfalls:
- Logging an object shows its current state. In browser dev tools, an object logged early and changed later can appear with its later values when you expand it. Log a copy (
structuredClone(obj)) or specific fields. - Leaving debug logs in production. They add noise and can expose personal data. Remove them or route them through a logger with levels.
Asynchronous code
Section titled βAsynchronous codeβJavaScript runs your code on one thread. Work that takes time, such as a network request, a timer or reading a file, is started and then finishes later; meanwhile the program keeps running. When the work completes, its callback is queued, and the event loop runs queued callbacks once the current code has finished. Promise reactions (microtasks) run before timer callbacks.
There are three styles for handling a result that arrives later:
- Callbacks: pass a function to be called later, as in
setTimeout(fn, 1000). Nesting several of them becomes hard to read. - Promises (ES2015): an object representing a future value that is pending, then fulfilled or rejected. Chain
.then()for results and.catch()for errors. async/await(ES2017): anasyncfunction always returns a promise, andawaitpauses that function (not the whole program) until a promise settles. Errors are handled with ordinarytry/catch.
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fetchOrder(id) { await wait(20); // stands in for a network call if (id === "A-404") throw new Error(`Order ${id} not found`); return { id, total: 42 };}
console.log("1. start");setTimeout(() => console.log("4. timer callback"), 0);Promise.resolve().then(() => console.log("3. promise reaction"));console.log("2. end of synchronous code");
await wait(5);
fetchOrder("A-1001").then((order) => console.log("5. then():", order.total));
async function show(id) { try { const order = await fetchOrder(id); console.log("6. await:", order.id, order.total); } catch (error) { console.log("7. caught:", error.message); }}await show("A-1002");await show("A-404");
const forgotAwait = fetchOrder("A-1003");console.log("8. without await:", forgotAwait instanceof Promise);Output:
1. start2. end of synchronous code3. promise reaction4. timer callback5. then(): 426. await: A-1002 427. caught: Order A-404 not found8. without await: trueThis sample uses await at the top level of the file, which works only in ES modules (.mjs files or "type": "module"); see Top-level await.
Pitfalls:
- Forgetting
await. You get aPromiseobject instead of the value, and its errors escape yourtry/catch. - Expecting
setTimeout(fn, 0)to run immediately. It runs after the current code and after already-queued promise reactions. - Unhandled rejections. A rejected promise with no
catchcrashes a Node.js process by default. Alwaysawaitinsidetry/catchor attach.catch().
Choosing between them
Section titled βChoosing between themβ| Need | Use |
|---|---|
| One of several fixed values | switch, or an object lookup table |
| Walk an array or other iterable | for...of |
| Walk an objectβs keys | Object.keys(obj) with for...of, or for...in for plain objects |
| Report a problem the caller must handle | throw new SomeError(...) |
| Add context to a low-level error | throw new Error("...", { cause }) |
| Inspect a list of records while debugging | console.table() |
| Wait for a result that arrives later | await inside an async function |
Interview questions
Section titled βInterview questionsβ1. What is the difference between for...of and for...in?
for...of iterates the values produced by an iterable (arrays, strings, maps, sets). for...in iterates the enumerable string property names of an object, including inherited ones. Use for...of for arrays.
2. When does finally run?
After the try block and any catch block, whether the code completed, threw, or returned early. A return inside finally replaces any earlier return value and discards a pending error, so avoid returning from it.
3. Why extend Error instead of throwing a plain object?
Subclasses keep the stack trace and message, work with instanceof, and are recognized by tools and loggers. You can add fields such as code or field for callers.
4. What does an async function return, and what does await block?
It always returns a promise: the returned value becomes the fulfillment value and a thrown error becomes the rejection. await pauses only that function; other code and callbacks keep running.
5. Senior scenario: a Node.js job processes 10,000 orders with orders.forEach(async (o) => { await save(o); }) and logs βdoneβ right after. Some saves fail silently and βdoneβ prints first. Why, and how do you fix it?
forEach ignores the promises returned by the async callback, so nothing waits for them and their rejections are unhandled. Use for...of with await for sequential processing, or batches with Promise.allSettled() for bounded parallelism, then report failures before logging βdoneβ.
Related pages
Section titled βRelated pagesβ- Values, types and operators: the previous step.
- Functions, scope and closures: the next step.
- Async and modules: promises and
async/awaitin depth. - Error cause: chaining errors with
{ cause }. - Optional catch binding:
catch { }without a parameter. - forβ¦of and forβ¦in: the two loops in depth.