Script Valley
Reading Other People's Code
Debugging Code You've Never SeenLesson 4.2

How to use console.log strategically when debugging unfamiliar code

strategic log placement, logging intermediate values, console.log vs console.dir vs console.table, removing debug logs, structured logging, log levels

Log the State, Not the Step

Strategic log placement diagram

Beginners log to confirm code runs. Experts log to inspect values. The question you're answering with every log is: "what is the actual value of X at this point?" โ€” not "did the code reach here?"

Strategic Placement

async function processOrder(orderId) {
  console.log('[processOrder] input:', orderId); // 1. log input

  const order = await db.orders.findById(orderId);
  console.log('[processOrder] fetched order:', order); // 2. log after async

  const validated = validateOrder(order);
  console.log('[processOrder] validated:', validated); // 3. log after transform

  const result = await chargeCustomer(validated);
  console.log('[processOrder] charge result:', result); // 4. log side effect result

  return result;
}

Better Than console.log

// console.dir: deep object inspection with full nesting
console.dir(complexObject, { depth: null });

// console.table: compare arrays of objects visually
console.table(users.slice(0, 5));

// JSON.stringify with indent: see full structure
console.log(JSON.stringify(data, null, 2));

// Label logs clearly so you can remove them later
console.log('[DEBUG][UserService.findById] result:', user);

Always prefix debug logs with a tag like [DEBUG] and your context. This makes them grep-able during investigation and findable for deletion when you're done. Committed debug logs are a code smell that signals the feature wasn't properly understood before shipping.

Up next

How to use a debugger to step through unfamiliar code

Sign in to track progress

How to use console.log strategically when debugging unfamiliar code โ€” Debugging Code You've Never Seen โ€” Reading Other People's Code โ€” Script Valley โ€” Script Valley