← Learning Hub
Intermediate

Errors and Debugging

Errors happen to everyone. Good programs expect them and handle them politely. Wrap risky code in try; if something goes wrong, catch runs.

Every developer spends a lot of time debugging - finding out why code doesn't do what you expected. It's a skill you get better at, not a sign that you're bad at programming. The steps are always similar: read the error message carefully, find the line it points to, check what values your variables actually hold, and change one thing at a time.

Example
function parseOrder(text) {
  try {
    const order = JSON.parse(text);
    return "Order " + order.id;
  } catch (err) {
    return "Bad order data: " + err.name;
  } finally {
    console.log("Parsing finished");
  }
}

console.log(parseOrder('{"id": 7}'));
// Output:
// Parsing finished
// Order 7
console.log(parseOrder("not json"));
// Output:
// Parsing finished
// Bad order data: SyntaxError

Throwing your own errors

Example
function setQuantity(qty) {
  if (!Number.isInteger(qty) || qty < 1) {
    throw new RangeError("Quantity must be 1 or more");
  }
  return qty;
}

try {
  setQuantity(0);
} catch (e) {
  console.log(e.name + ": " + e.message);   // Output: RangeError: Quantity must be 1 or more
}

Common error types

  • ReferenceError - using a variable that doesn't exist (often a typo)
  • TypeError - using a value the wrong way, like calling something that isn't a function, or reading a property of undefined
  • SyntaxError - the code itself is written wrong (a missing bracket)
  • RangeError - a number is out of the allowed range

Debugging in the browser

  • Press F12 to open DevTools and look at the Console tab for red errors. Click the file name to jump to the line.
  • Use console.log(value) to see what a variable holds, and console.table(array) for lists of objects.
  • Write debugger; in your code, or click a line number in the Sources tab, to pause there and look at every variable.
  • Read the error message slowly: it tells you the type, the reason and the line.
Don't hide errors with an empty catch {}. At least log them, and show the user a helpful message.
Key points
  • try / catch / finally handle errors.
  • throw new Error("...") reports problems from your code.
  • Read the error type and line in the Console.
  • Use console.log, console.table and breakpoints to inspect values.

📝 Test yourself

1. Which block always runs, error or not?
2. Reading user.name when user is undefined gives a...
3. Fill in the keyword that creates your own error:
new Error("Out of stock");