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
| Kind | What happens | Example |
|---|---|---|
| Syntax error | The code can't even be read; nothing in that script runs | A missing ) or } |
| Runtime error | The code starts, then crashes at one line | Calling a function that doesn't exist |
| Logic error | No error message, but the answer is wrong | a + 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
| Message | Usual cause |
|---|---|
X is not defined | Typo in a name, or the variable is out of scope |
Cannot read properties of null | getElementById found nothing (wrong id, or the script ran too early) |
X is not a function | Typo in a method name (getElementByID), or calling something that isn't a function |
Unexpected token | Missing or extra bracket, comma or quote |
Assignment to constant variable | Changing 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:
<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
<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
- Open the console. Is there a red error? Read it and go to the line it names.
- Check spelling and capital letters of every name on that line.
- Check brackets: every
(,{and[needs its partner. console.logthe values just before the problem line. Are they what you expected? Are numbers really numbers?- Simplify: comment out half of the code to find which half has the bug.
- 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. 🙂
By Sir Reyel · Last updated 2026-12-04