JuniorJavaScript

How is a breakpoint different from console.log when debugging? When do you still use console.log?

A breakpoint pauses the program on one line and lets you see the value and type of every variable, see who called the function (the call stack), and type more expressions that are evaluated right in that context. console.log only prints what you guessed in advance you'd need.

One example shows the difference: a menu price was stored by mistake as the string "35.000" (thirty-five thousand, written with a dot between the thousands as in Vietnam and much of Europe). console.log(item.price) prints 35.000, which looks like a perfectly normal price. In the debugger's Variables panel the value shows up with quotes, and typeof returns 'string'. The bug is obvious at once: "35.000" * 2 is 70, because JavaScript reads the dot as a decimal point.

Tools worth mentioning: conditional breakpoints (only stop when order.id === 1044), Watch, the Debug Console, the Call Stack, and logpoints (log without pausing and without editing the code).

console.log still makes sense:

  • in a small script you run once;
  • for timing bugs, where pausing the program changes the order things run in;
  • in production, where you can't attach a debugger, and there you should write structured logs.

Bonus points: logging JSON.stringify(value) or { value } makes it clear whether you have a string or a number.