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

Growing Arrays and Objects

Recognizing unbounded caches, logs, or collections that accumulate data indefinitely without pruning strategies.

Growing Arrays and Objects

What you'll learn: How unbounded collections that accumulate data without limits can slowly drain memory and crash your application.

The Unlimited Growth Problem

A memory leak doesn't always require a mistake—sometimes the code works exactly as designed, but the design itself is flawed. When you continuously add items to an array, object, or Map without ever removing old entries, you create a growing collection that consumes more memory over time until your application slows to a crawl or crashes.

Common Culprits

Logging without limits:

const requestLog = [];
app.on('request', (req) => {
  requestLog.push({ url: req.url, timestamp: Date.now() });
  // Never removes old entries!
});

Unbounded caching:

const userCache = {};
function getUser(id) {
  if (!userCache[id]) {
    userCache[id] = fetchUserFromDB(id);
  }
  return userCache[id];
  // Cache grows forever as new users are accessed
}

Accumulating metrics or history:

const metrics = [];
setInterval(() => {
  metrics.push({ memory: process.memoryUsage(), time: Date.now() });
}, 1000);
// Adds 86,400 entries per day with no cap

Why It Matters

Unlike accidental globals or forgotten timers, these leaks happen gradually. Your app might run fine for days, then suddenly hit a memory ceiling during a traffic spike or after weeks of uptime.

Key Takeaway: Always implement pruning strategies for collections that accumulate data—set maximum sizes, use LRU caches, rotate logs, or implement time-based expiration to prevent unbounded growth.