Debugging JavaScript
Every programmer writes bugs. Good programmers are not the ones who never make mistakes — they are the ones who can find them quickly. This lesson teaches two tools: console.log and reading error messages.
Each section has a small program you can edit. Press Run (or Ctrl/⌘ + Enter) and the output appears below, just as if you ran node main.js in a terminal. Your edits are saved in this browser — Reset brings back the original code.
Summary
Your debugging checklist
- Read the error. All of it. The type (
SyntaxError,ReferenceError,TypeError) tells you what kind of mistake it is. The message tells you which name or symbol is the problem. - Find the line number — in the first line (
main.js:4) or in the firstat …line that mentions your file. Ignore thenode:internallines. - Look at that line, and the line before it. The
^shows where JavaScript got confused; the real mistake is often a little earlier. - Fix one thing, then run again. Programs often have several bugs; you will only see the next one after fixing the first.
- No error but wrong result? That is a logic bug. Add
console.log("name:", name, typeof name)before and after the suspicious line and compare what you see with what you expected. - Clean up. Remove your debug
console.loglines when the bug is fixed.
The error message is not the computer being angry at you. It is the computer trying to help — it is telling you exactly where to look.