DEV Community

Arhan Khan
Arhan Khan

Posted on

Debugging JavaScript for Beginners: console, Breakpoints and the debugger Statement

Every developer debugs. The difference between a beginner and an experienced developer is not that the experienced one writes bug-free code — it is that they find bugs faster. Debugging is a skill with real tools, and the best ones are already in your browser.

Start with console.log, but use it well. Log the actual values, not just "here" — and learn its more useful cousins. console.table prints arrays and objects as a readable table, console.error marks a message as an error, and console.time measures how long a piece of code takes.

console.table(users);
console.time("fetch");
await fetchData();
console.timeEnd("fetch"); // fetch: 342.15ms
Enter fullscreen mode Exit fullscreen mode

The real power tool is the breakpoint. Open DevTools, go to the Sources tab, click a line number, and the browser will pause your code exactly there. While paused, you can hover over any variable to see its value, step through line by line, and watch how your data changes. This beats scattering console.log everywhere, because you see the whole state at once instead of guessing which line to log.

function totalPrice(items) {
  debugger; // pauses here when DevTools is open
  return items.reduce((sum, item) => sum + item.price, 0);
}
Enter fullscreen mode Exit fullscreen mode

The debugger statement does the same thing from inside your code: when DevTools is open, execution pauses on that line. It is handy when the bug only appears in a specific situation — put it inside an if so it only pauses when the bad case actually happens.

A few habits make debugging far less painful. Read the error message first — it usually tells you the file, the line, and what went wrong. Reproduce the bug reliably before you try to fix it. Change one thing at a time, and check whether it helped. And when you are stuck, explain the code out loud, line by line, as if to a beginner: most bugs reveal themselves the moment you describe what the code actually does instead of what you meant it to do.

Top comments (0)