Aral Code

Going Further Lesson 28 of 30

JavaScript Errors and Debugging

Read error messages, find bugs with console.log and the browser DevTools, and handle problems gracefully with try, catch, finally and throw.

Every programmer writes bugs, every day. What separates beginners from experts isn't fewer mistakes; it's knowing how to find and fix them quickly. This lesson teaches you to read error messages, debug like a pro, and handle errors so your page doesn't break.

Three kinds of errors

KindWhat happensExample
Syntax errorThe code can't even be read; nothing in that script runsA missing ) or }
Runtime errorThe code starts, then crashes at one lineCalling a function that doesn't exist
Logic errorNo error message, but the answer is wronga + b / 2 instead of (a + b) / 2

Logic errors are the sneakiest, because the browser doesn't warn you. Test your code with values whose answers you already know.

Reading an error message

Open the console (F12) and you'll see something like:

Uncaught ReferenceError: totl is not defined
    at computeTotal (script.js:14:3)
  • ReferenceError: the type of error
  • totl is not defined: what went wrong (a typo of total)
  • script.js:14:3: the file, line 14, column 3

The most common errors

MessageUsual cause
X is not definedTypo in a name, or the variable is out of scope
Cannot read properties of nullgetElementById found nothing (wrong id, or the script ran too early)
X is not a functionTypo in a method name (getElementByID), or calling something that isn't a function
Unexpected tokenMissing or extra bracket, comma or quote
Assignment to constant variableChanging a const

Debugging with console.log

When the answer is wrong, print values along the way to see where things go off track:

function average(grades) {
  let total = 0;
  for (const g of grades) {
    total += g;
    console.log("added", g, "total is now", total);
  }
  console.log("count:", grades.length);
  return total / grades.length;
}
average(["88", "91"]);

Console

added 88 total is now 088
added 91 total is now 08891
count: 2

The log shows instantly that the grades were strings being joined, not numbers being added. The fix: total += Number(g);.

The debugger

In DevTools, open the Sources tab, find your file and click a line number to set a breakpoint. When the code reaches that line, it pauses, and you can hover over variables to see their values and step through line by line. You can also write the word debugger; in your code to pause there when DevTools is open.

try…catch: handling errors gracefully

Some errors you can't prevent, like bad data from a user or a server. Wrap risky code in try, and handle the problem in catch instead of letting the whole script crash:

Example try…catch
<textarea id="json" rows="3" cols="36">{"name": "Ana", "grade": 9}</textarea><br>
<button id="go">Read JSON</button>
<p id="out"></p>
<script>
  document.getElementById("go").addEventListener("click", () => {
    const out = document.getElementById("out");
    try {
      const data = JSON.parse(document.getElementById("json").value);
      out.textContent = `✅ ${data.name} is in Grade ${data.grade}.`;
    } catch (err) {
      out.textContent = "❌ That isn't valid JSON: " + err.message;
    } finally {
      console.log("Finished checking.");
    }
  });
</script>

Try deleting a quote or a bracket in the box. finally runs whether there was an error or not, which is useful for cleanup, like hiding a "Loading…" message.

throw: creating your own errors

Example Throwing an error for invalid input
<pre id="out"></pre>
<script>
  function setGrade(g) {
    if (g < 0 || g > 100) {
      throw new Error(`Invalid grade: ${g}. It must be from 0 to 100.`);
    }
    return g;
  }

  let log = "";
  for (const g of [95, 150]) {
    try {
      log += "Saved " + setGrade(g) + "\n";
    } catch (e) {
      log += "Problem: " + e.message + "\n";
    }
  }
  document.getElementById("out").textContent = log;
</script>

A debugging checklist

  1. Open the console. Is there a red error? Read it and go to the line it names.
  2. Check spelling and capital letters of every name on that line.
  3. Check brackets: every (, { and [ needs its partner.
  4. console.log the values just before the problem line. Are they what you expected? Are numbers really numbers?
  5. Simplify: comment out half of the code to find which half has the bug.
  6. Explain your code out loud, line by line, to a classmate (or a rubber duck 🦆). You'll often spot the mistake while explaining.

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. Which error gives a wrong answer with no error message?
2. What does "X is not defined" usually mean?
3. When does the finally block run?
4. What does throw new Error("...") do?

By Sir Reyel · Last updated 2026-12-04