Skip to content

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.

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 decides which statements run and in what order. JavaScript gives you three kinds of tools:

  • Conditionals: if/else if/else for general conditions; the conditional (ternary) operator cond ? a : b when you need a value; switch when one value is compared against several fixed cases.
  • Loops: for (let i = 0; i < n; i++) when you need an index; for...of to walk the values of an array, string, Map, Set or any other iterable; for...in to walk an object’s enumerable property names (including inherited ones); while and do...while when you loop until a condition changes.
  • Jumps: break leaves the loop or switch, continue skips to the next iteration, and return leaves 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, large
A-1002: waiting for payment, small
A-1004: in progress, small
revenue: 170
paid -> 1
pending -> 1
stopped at attempt 2

Pitfalls:

  • for...in on arrays. It yields string indexes, can include inherited properties and is not meant for arrays. Use for...of.
  • Missing break in switch. Execution falls through into the next case. Return from each case, or add break deliberately.
  • Assignment in a condition. if (status = "paid") assigns and is always truthy. Use ===.

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 characters
ValidationError: Invalid quantity: 0
checked 24 characters
ValidationError: Order is not valid JSON
caused by SyntaxError
checked 12 characters

Pitfalls:

  • Throwing strings. throw "failed" has no stack trace and no name. Throw new Error("failed").
  • Swallowing errors. An empty catch {} hides bugs. Handle the errors you expect and rethrow the rest.
  • try around async work without await. A try block only catches a rejected promise if you await it inside the block; see Asynchronous code.

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() and console.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() and console.groupEnd() indent related lines.
  • console.count(label) counts how many times a line ran.
  • console.time(label) and console.timeEnd(label) measure elapsed time and print something like load: 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.

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:

  1. Callbacks: pass a function to be called later, as in setTimeout(fn, 1000). Nesting several of them becomes hard to read.
  2. Promises (ES2015): an object representing a future value that is pending, then fulfilled or rejected. Chain .then() for results and .catch() for errors.
  3. async/await (ES2017): an async function always returns a promise, and await pauses that function (not the whole program) until a promise settles. Errors are handled with ordinary try/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. start
2. end of synchronous code
3. promise reaction
4. timer callback
5. then(): 42
6. await: A-1002 42
7. caught: Order A-404 not found
8. without await: true

This 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 a Promise object instead of the value, and its errors escape your try/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 catch crashes a Node.js process by default. Always await inside try/catch or attach .catch().
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

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”.