Debugging Tips & Tricks
Debugging is the work of finding out what code actually does, as opposed to what it was meant to do. Most people start with console.log(), but the console object has methods that count, time, group and tabulate output, and the browser’s developer tools can pause a script and show every variable at that moment.
The examples run in Node.js, and the same methods work in the browser console, where the output looks slightly different.
Counting calls
Section titled “Counting calls”console.count() prints a label and the number of times it has been called with that label, which shows how often a piece of code runs. console.countReset() sets a label back to zero.
const checkout = (customer) => { console.count(customer);};
checkout('Asha');checkout('Ben');checkout('Asha');console.countReset('Asha');checkout('Asha');This prints:
Asha: 1Ben: 1Asha: 2Asha: 1Tables
Section titled “Tables”console.table() shows an array of objects as a table, which is far easier to scan than the nested output of console.log(). A second argument picks the columns.
const books = [ { title: 'Emma', author: 'Austen', year: 1815 }, { title: 'Dracula', author: 'Stoker', year: 1897 }, { title: 'Middlemarch', author: 'Eliot', year: 1871 },];
console.table(books);console.table(books, ['title', 'year']);This prints:
┌─────────┬───────────────┬──────────┬──────┐│ (index) │ title │ author │ year │├─────────┼───────────────┼──────────┼──────┤│ 0 │ 'Emma' │ 'Austen' │ 1815 ││ 1 │ 'Dracula' │ 'Stoker' │ 1897 ││ 2 │ 'Middlemarch' │ 'Eliot' │ 1871 │└─────────┴───────────────┴──────────┴──────┘┌─────────┬───────────────┬──────┐│ (index) │ title │ year │├─────────┼───────────────┼──────┤│ 0 │ 'Emma' │ 1815 ││ 1 │ 'Dracula' │ 1897 ││ 2 │ 'Middlemarch' │ 1871 │└─────────┴───────────────┴──────┘Grouping output
Section titled “Grouping output”console.group() indents everything logged after it until the matching console.groupEnd(), and groups can be nested. In the browser, each group can also be collapsed.
const order = { id: 1042, lines: [{ sku: 'MUG-01', qty: 2 }] };
console.group(`Order ${order.id}`);console.log('Validating');console.group('Lines');for (const line of order.lines) { console.log(`${line.sku} x ${line.qty}`);}console.groupEnd();console.log('Done');console.groupEnd();console.log('Next order');This prints:
Order 1042 Validating Lines MUG-01 x 2 DoneNext orderChecking assumptions
Section titled “Checking assumptions”console.assert() prints its message only when the condition is false, so it can stay in the code and report only when something is wrong. It does not throw or stop the program.
const stock = { teapot: 4, mug: -1 };
for (const [product, level] of Object.entries(stock)) { console.assert(level >= 0, `Stock for ${product} is negative:`, level);}console.log('Check finished');This prints:
Assertion failed: Stock for mug is negative: -1Check finishedconsole.error() and console.warn() work like console.log(), but browsers show their messages in red or yellow and let the console filter by level, and in Node.js they write to the error stream instead of standard output. console.assert() also writes to the error stream.
Timing code
Section titled “Timing code”console.time() starts a timer with a label, and console.timeEnd() with the same label stops it and prints how long it ran. console.timeLog() prints the time so far without stopping it.
console.time('sort');const numbers = Array.from({ length: 200_000 }, () => Math.random());numbers.sort((a, b) => a - b);console.timeEnd('sort');This prints:
sort: 56.012msThe figure changes from run to run, so time code several times before drawing a conclusion. The Performance panel in the browser’s developer tools gives a fuller picture.
Seeing all of a nested object
Section titled “Seeing all of a nested object”console.log() in Node.js follows nested objects to a depth of two by default and shows [Object] for anything deeper. console.dir() with depth: null shows the whole object.
const settings = { theme: { colours: { primary: { hex: '#0055aa' } } } };
console.log(settings);console.dir(settings, { depth: null });This prints:
{ theme: { colours: { primary: [Object] } } }{ theme: { colours: { primary: { hex: '#0055aa' } } }}The browser console does not cut objects short, but it shows them as they are when expanded, not as they were when logged. If an object changes after it is logged, expanding it shows the new values. Logging structuredClone(settings) or JSON.stringify(settings) records a copy as it stood at that moment.
Pausing with the debugger
Section titled “Pausing with the debugger”The debugger statement pauses the script at that line, but only while the developer tools are open. While paused, the tools show the value of every variable in scope and the call stack that led there, and the code can be run one line at a time.
<button id="total">Work out the total</button>const prices = ['4.50', '2.25', '3.00'];
document.getElementById('total').addEventListener('click', () => { let total = 0; for (const price of prices) { debugger; total += price; } console.log(total);});With the developer tools open, clicking the button pauses the script inside the loop. Stepping through shows total becoming the string "04.50" rather than the number 4.5, because the prices are strings, so += joins them instead of adding them. Without the developer tools open, the button simply logs 04.502.253.00.
A breakpoint set in the Sources panel, by clicking a line number, does the same job without changing the code, and it cannot be left in by mistake. Right-clicking a line number also offers a conditional breakpoint, which pauses only when an expression is true, and a logpoint, which logs a message without pausing. A debugger statement left in shipped code pauses the page for any user who has the developer tools open, so remove it once the bug is found.
Steve Griffith covers this topic in his video Debugging JavaScript Tips, Tricks, and Best Practices.