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

  1. 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.
  2. Find the line number — in the first line (main.js:4) or in the first at … line that mentions your file. Ignore the node:internal lines.
  3. Look at that line, and the line before it. The ^ shows where JavaScript got confused; the real mistake is often a little earlier.
  4. Fix one thing, then run again. Programs often have several bugs; you will only see the next one after fixing the first.
  5. 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.
  6. Clean up. Remove your debug console.log lines 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.