Course contentsShow
← JavaScript
Lesson 1878 of 2,72339. Memory Management and GCFree lesson

Console.log in Production Code

How logged objects are retained by DevTools and can prevent garbage collection when console is open.

Console.log in Production Code

You'll learn how seemingly harmless console.log() statements can prevent garbage collection and cause memory leaks.

The Hidden Cost of Logging Objects

When you log an object to the console, the browser's DevTools need to keep a reference to that object so you can inspect it later. This means the garbage collector cannot reclaim that memory, even if your code no longer references the object.

function processLargeData() {
  const hugeArray = new Array(1000000).fill({data: 'x'.repeat(100)});
  
  console.log('Processing:', hugeArray); // Keeps hugeArray in memory!
  
  // Even after this function ends, hugeArray cannot be GC'd
  // as long as DevTools console is open
}

The DevTools Console Trap

The problem intensifies when the console is open during development or testing:

  • Console closed: Logged objects can be garbage collected
  • Console open: Logged objects are retained indefinitely
  • Production with forgotten logs: Users with DevTools open experience memory bloat
// This seemingly innocent debug log creates a leak
setInterval(() => {
  const snapshot = captureAppState(); // Large object
  console.log('State:', snapshot); // Retained forever!
}, 1000);

Why This Matters

Unlike the circular references modern engines handle automatically (lesson 1877), console retention is intentional browser behavior. The DevTools must keep these objects alive for you to inspect them. Remove or conditionally disable console logs in production to avoid this trap.

Key Takeaway: console.log() prevents garbage collection of logged objects when DevTools is open, making forgotten debug logs a real memory leak risk in production code. Always strip or gate logging before deploying.