← Back to JavaScript, page 10

javascript-0200 · Medium mid

How do you debug JavaScript effectively with browser DevTools, and how do source maps connect minified code to the original source?

Use breakpoints (line, conditional, logpoint, DOM, event, and exception breakpoints), the call stack and scope panels, watch expressions, and the console beyond console.log. A source map is a JSON file that maps positions in generated code back to the original files, so DevTools and error monitors can show the real file, line, and name. Reproduce first, narrow down the cause, and check the network and performance panels when the bug is not in the logic.

Full answer

A good debugging routine matters more than any one tool: reproduce the bug, make the failure small, form a hypothesis, test it, and fix the cause instead of the symptom.

Tools in browser DevTools (Chrome, Firefox, and Safari have similar ones):

  • Sources panel and the debugger statement pause execution. Breakpoint types: line, conditional (pauses only when an expression is true), logpoint (prints without editing code), DOM change breakpoints (on subtree, attribute, or removal), XHR or fetch breakpoints, event listener breakpoints (click, keydown), and pause on caught or uncaught exceptions.
  • When paused: the call stack shows how you got here (async stack traces show awaits and promise chains), the scope panel shows local, closure, and global variables, and watch expressions track values. Step over, into, out, and "blackbox" library code you do not want to step into.
  • Console: console.table for arrays of objects, console.group to organize output, console.error and console.warn with stack traces, console.assert, console.count, console.time, and console.dir. $0 is the selected element, $_ is the last result, and copy(value) copies to the clipboard. Live expressions track values.
  • Network panel for failed requests, status codes, payloads, timing, CORS errors, and throttling. Performance panel for long tasks and layout work, and Memory panel for heap snapshots to find leaks. Application panel for storage, cookies, and service workers.
  • Local overrides and "preserve log" help with hard-to-reproduce issues. In Node.js, run node --inspect or --inspect-brk and attach the same DevTools.

Source maps: bundlers and compilers (esbuild, Webpack, Babel, TypeScript) produce minified or transformed code that is hard to read. A .map file (version 3 format) contains sources, names, and mappings, which are encoded segments (VLQ) that map each position in the generated file to a position in an original file. The generated file ends with a //# sourceMappingURL= comment, and DevTools loads the map and shows the original files. Node.js uses --enable-source-maps to rewrite stack traces. Error monitoring tools upload maps and resolve stacks on the server.

Practices: do not publish source maps with source content to the public if the code is private (upload them privately to your error monitor), use sourcesContent when you need the source in DevTools, and keep the map version matched to the deployed file.

Common mistakes: debugging only with console.log in production-like loops, forgetting that a value in the console is a live reference (it shows the current state of an object, not what it was when logged), and fixing symptoms.

javascript
const esbuild = require('esbuild');
const { SourceMap } = require('node:module');
const vm = require('node:vm');

const original = `// price.ts
export function applyDiscount(price, percent) {
  if (percent > 100) {
    throw new RangeError('percent must be 100 or less');
  }
  const discountAmount = (price * percent) / 100;
  return price - discountAmount;
}

export function checkout(items, percent) {
  const total = items.reduce((sum, item) => sum + item.price, 0);
  return applyDiscount(total, percent);
}
globalThis.run = () => checkout([{ price: 40 }, { price: 60 }], 150);
`;

const result = esbuild.transformSync(original, {
  minify: true,
  sourcemap: 'external',
  sourcefile: 'price.ts',
  format: 'iife',
  loader: 'js',
});

const map = JSON.parse(result.map);
console.log('minified code:', result.code.trim().slice(0, 150) + '...');
console.log('map version:', map.version, '| sources:', map.sources, '| names listed:', map.names.length, '| mappings length:', map.mappings.length > 20);

const sandbox = {};
vm.runInNewContext(result.code, sandbox, { filename: 'bundle.min.js' });
let stackLine;
try {
  sandbox.run();
} catch (error) {
  stackLine = error.stack.split('\n').find((line) => line.includes('bundle.min.js'));
  console.log('error:', error.name, error.message);
  console.log('minified frame:', stackLine.trim().replace(/\(.*[\\/]/, '('));
}

const [, line, column] = stackLine.match(/bundle\.min\.js:(\d+):(\d+)/);
const sourceMap = new SourceMap(map);
const entry = sourceMap.findEntry(Number(line) - 1, Number(column) - 1);
const originalLines = original.split('\n');
console.log(`mapped back to: ${entry.originalSource}:${entry.originalLine + 1}:${entry.originalColumn + 1}`);
console.log('original code at that position:', originalLines[entry.originalLine].trim());

const withContent = esbuild.transformSync('const answer = 40 + 2;\nconsole.log(answer);', { sourcemap: 'external', sourcefile: 'a.js', sourcesContent: true });
console.log('sourcesContent included:', Array.isArray(JSON.parse(withContent.map).sourcesContent));

const user = { name: 'Asha', tags: ['js'] };
const snapshot = JSON.stringify(user);
user.tags.push('css');
console.log('logged value is live in DevTools; the snapshot taken at log time was:', snapshot);

Run with Node.js v24.22.1 as js-200.js; two runs gave identical output. Output: minified code: (()=>{function c(t,o){if(o>100)throw new RangeError("percent must be 100 or less");const r=t*o/100;return t-r}function u(t,o){const r=t.reduce((n,e)=>... map version: 3 | sources: [ 'price.ts' ] | names listed: 9 | mappings length: true error: RangeError percent must be 100 or less minified frame: at c (bundle.min.js:1:38) mapped back to: price.ts:4:11 original code at that position: throw new RangeError('percent must be 100 or less'); sourcesContent included: true logged value is live in DevTools; the snapshot taken at log time was: {"name":"Asha","tags":["js"]}

Key points

  • Use breakpoints of many kinds, the call stack, scope, watch, and async stacks, not only console.log.
  • Know console.table, group, assert, time, and copy; use the network, performance, and memory panels when relevant.
  • A source map is JSON that maps generated positions to original files, lines, columns, and names.
  • Node.js can rewrite stacks with --enable-source-maps; error tools resolve stacks on the server.
  • Keep maps matched to releases and private when the source is private.

Common mistakes

  • Debugging only with console.log when a breakpoint would show the whole state.
  • Shipping source maps with full source to a public site by accident.
  • Using a map that does not match the deployed file, which shows wrong lines.
  • Forgetting that console shows live object references.

Follow-ups

  • How does Node.js apply source maps to stack traces?
  • What do the mappings in a source map encode?
  • How would you debug an issue that only happens in production?

Tips

  • Start with the debugging routine, then the tools.
  • Name conditional breakpoints and logpoints; they are underused.
  • Explain a source map as a lookup from generated position to original position.