Skip to content
Velloreth
Programming 7 min read

Debugging JavaScript With the Console: Beyond console.log

The console has more than log. Learn table, group, time, trace, and the DevTools features that make debugging faster.

By

The console methods

log

The default. Prints a string representation.

console.log('value:', value);

Multiple arguments are printed space-separated, which is cleaner than string concatenation.

table

Renders an array of objects as a table.

const users = [
  { id: 1, name: 'Ada', role: 'admin' },
  { id: 2, name: 'Grace', role: 'user' },
];

console.table(users);

The output is a real table with columns for each property, which is far more readable than a list of collapsed objects. You can also select columns:

console.table(users, ['name', 'role']);

group and groupEnd

Nests related output.

console.group('User processing');
console.log('Loading user');
console.log('Validating');
console.groupEnd();

console.groupCollapsed starts collapsed, which is useful for verbose sections.

time and timeEnd

Measures elapsed time.

console.time('fetch');
await fetchData();
console.timeEnd('fetch'); // fetch: 234.5ms

console.timeLog('fetch') prints an intermediate reading without ending the timer.

trace

Prints a stack trace.

function process() {
  console.trace('reached process');
}

This shows how the code was reached, which is invaluable when a function is called from many places.

assert

Logs only when the condition is false.

console.assert(user.id, 'user has no id');

count

Counts how many times a line is reached.

console.count('loop'); // loop: 1, loop: 2, ...

dir

Prints an object’s properties rather than its string representation.

console.dir(document.body);

For a DOM element, log prints the HTML and dir prints the element’s properties. dir is usually more useful for inspection.

warn and error

Styled differently and filterable in DevTools.

console.warn('deprecated');
console.error('failed');

console.error also includes a stack trace.

The live reference trap

DevTools stores a live reference to a logged object.

const state = { count: 0 };
console.log(state);
state.count = 5;
// Expanding the log shows count: 5, not 0

The log shows the object’s current state, not its state at log time. This is a frequent source of confusion.

The fixes:

// Snapshot the value
console.log(JSON.stringify(state));

// Or clone it
console.log(structuredClone(state));

// Or use a breakpoint, which pauses at the exact moment

DevTools breakpoints

Breakpoints are usually better than console statements, because they do not require editing the source and they pause execution.

Line breakpoints

Click the line number in the Sources panel. Execution pauses there, and you can inspect every variable in scope.

Conditional breakpoints

Right-click a line number and choose “Add conditional breakpoint”. The breakpoint fires only when the condition is true.

user.id === 42

This is invaluable in a loop, where an unconditional breakpoint fires thousands of times.

Logpoints

Right-click a line number and choose “Add logpoint”. It logs a message without pausing and without editing the source.

user id: ${user.id}, count: ${count}

Logpoints are the best option for production debugging, because the source is not modified.

DOM breakpoints

Right-click an element in the Elements panel and choose “Break on” — subtree modifications, attribute modifications, or node removal. Execution pauses when the change happens, which finds the code responsible.

Event listener breakpoints

The Sources panel can break on any event, such as click or fetch. Useful when you do not know which handler is running.

XHR/fetch breakpoints

Break when a request matches a URL pattern. Useful for finding which code makes a request.

The debugger statement

function process(data) {
  debugger; // pauses here when DevTools is open
  return transform(data);
}

The debugger statement pauses execution when DevTools is open and does nothing otherwise. It is useful for a quick pause without finding the file in DevTools.

Inspecting scope

When paused, the Scope panel shows:

  • Local — variables in the current function.
  • Closure — variables from enclosing scopes.
  • Global — the global object.

The Closure section is particularly useful for understanding closures, because it shows exactly what each function has captured.

The call stack

When paused, the Call Stack panel shows the chain of calls that reached the current line. Clicking a frame switches to that context, so you can inspect the variables at each level.

This is the interactive equivalent of reading a stack trace.

Watch expressions

Add an expression to the Watch panel and it is evaluated on every pause.

user.items.filter(i => i.active).length

This is useful for tracking a derived value across steps.

The Performance panel

For performance problems, the Performance panel records a profile and shows a flame graph of where time went.

  1. Click Record.
  2. Interact with the page.
  3. Stop.
  4. Inspect the flame graph.

Look for long tasks, layout thrashing, and functions that appear repeatedly.

The Network panel

For request problems:

  • Status codes — 4xx and 5xx are highlighted.
  • Timing — the waterfall shows where time went.
  • Payload — the request body and headers.
  • Response — the response body.
  • Preserve log — keeps requests across navigations.

Debugging async code

Async code is harder to debug because the stack does not show the scheduling call.

Enable async stack traces. Modern DevTools links async frames, showing “async” markers in the call stack. Node has --async-stack-traces, on by default in recent versions.

Log at the boundaries. Log when a promise is created and when it resolves, so you can see the ordering.

console.log('requesting');
const data = await fetchData();
console.log('received', data);

Use the Network panel for request problems, rather than logging around a fetch. It shows the actual request, response, timing, and headers.

Watch for unhandled rejections. An unhandled promise rejection is silent in some environments.

window.addEventListener('unhandledrejection', (e) => {
  console.error('Unhandled rejection:', e.reason);
});

Check the ordering. await yields to the microtask queue, so code after an await runs later than you might expect. Logging with timestamps makes the ordering visible.

Debugging in production

You cannot attach DevTools to a user’s browser, so the approach differs.

Log to a service. Send errors and key events to a logging service, with a correlation id so you can follow one session.

Use source maps. Upload them to the error service so minified stack traces resolve to the original code.

Add a debug flag. A URL parameter or a local storage key that enables verbose logging for a specific user.

const debug = new URLSearchParams(location.search).has('debug');
if (debug) console.log('state', state);

Capture the state at the error. A stack trace without the surrounding state is often not enough.

window.addEventListener('error', (e) => {
  reportError({
    message: e.message,
    stack: e.error?.stack,
    url: location.href,
    userAgent: navigator.userAgent,
  });
});

Do not log sensitive data. Production logs are widely readable and long-lived.

Practical guidance

  • Use console.table for arrays of objects.
  • Use console.group to nest related output.
  • Use console.time to measure elapsed time.
  • Use console.trace to see how code was reached.
  • Snapshot objects with structuredClone or JSON.stringify when logging.
  • Prefer breakpoints and logpoints over console statements.
  • Use conditional breakpoints in loops.
  • Use DOM breakpoints to find what changes an element.
  • Use the Performance panel for slow code.

For the related guides, see reading-stack-traces and debugging-with-breakpoints. For the broader context, logging-best-practices and debugging-strategies-that-work.

Quotable summary

The console has more than log: console.table renders arrays of objects as a table, console.group nests related output, console.time measures elapsed time, and console.trace prints a stack trace showing how the code was reached. DevTools stores a live reference to a logged object, so the log shows the object’s current state rather than its state at log time, which is why you should snapshot with structuredClone or JSON.stringify. Breakpoints, conditional breakpoints, and logpoints are usually better than console statements, because they do not require editing the source, and logpoints are the best option for production debugging. Use DOM breakpoints to find what changes an element, and the Performance panel for slow code.

Frequently asked questions

What is the difference between console.log and console.dir?
log prints a string representation, which for DOM elements is the HTML. dir prints the object's properties, which is more useful for inspecting an element's API.
How do I log an object without it being collapsed?
Use console.log(JSON.stringify(obj, null, 2)) for a readable snapshot, or console.dir(obj, { depth: null }) to expand all levels. DevTools collapses objects by default and shows a live reference.
What is a logpoint?
A logpoint is a breakpoint that logs a message instead of pausing. It is set in DevTools and does not require editing the source, which makes it ideal for production debugging.
What does console.assert do?
It logs a message only when the assertion is false. It is useful for checking an invariant without cluttering the console when everything is fine.
How do I measure how long code takes?
Use console.time('label') before and console.timeEnd('label') after. For more detail, use the Performance panel, which shows a flame graph of where time went.
Why does my logged object show the current value, not the value at log time?
Because DevTools stores a live reference to the object. By the time you expand it, the object has changed. Log a copy with structuredClone or JSON.stringify to capture the value at that moment.