Free beginner tutorial

JavaScript Debugging and Error Handling

Debugging is the process of finding and fixing a problem in code. Learn to read browser errors, inspect values, and handle expected failures without hiding problems from users.

Read the error message and stack trace

When JavaScript fails, the browser Console usually shows an error type, message, file and line number. A SyntaxError points to code the parser cannot read, a ReferenceError often means a name is unavailable, and a TypeError means an operation does not fit the value it received.

Start at the first useful message and follow the stack trace to the code that called the failing function. Fix the underlying cause instead of editing a later line that only reveals the problem.

Use the browser developer tools

Open the Console to read errors and inspect values. In the Sources or Debugger panel, set a breakpoint on a line to pause execution. Step through the next lines and inspect the variables to see how their values change.

const total = price * quantity;
console.log({ price, quantity, total });

Logging a labeled object can make it easier to spot an unexpected input. Remove temporary logs after you have solved the issue, or replace them with useful error reporting.

Handle an expected failure with try and catch

Use try...catch when an operation may fail and your code can respond in a useful way. This example catches malformed JSON and reports the problem:

const rawSettings = "{theme:dark}";

try {
  const settings = JSON.parse(rawSettings);
  console.log(settings);
} catch (error) {
  console.error("Settings could not be read:", error.message);
}

The catch block does not repair the invalid data. In a real interface, you could show a clear message, use a safe default, or ask the person to try again.

Throw a clear error for an invalid value

A function can throw an error when it receives a value outside its supported range. The calling code can then decide how to handle it:

function setRating(rating) {
  if (!Number.isFinite(rating) || rating < 0 || rating > 5) {
    throw new RangeError("Rating must be a number from 0 to 5.");
  }

  return rating;
}

Use a specific message that explains what went wrong and, when possible, how to provide a valid value.

Debug a problem step by step

  1. Reproduce the problem and note what you expected to happen.
  2. Read the Console message and identify the file and line.
  3. Inspect the inputs and pause at a breakpoint if the values are unclear.
  4. Fix the cause, then repeat the same steps to confirm the behavior.
Do not leave an empty catch block. If you cannot recover, report the failure clearly so it can be fixed instead of silently hiding it.