Memory Management

Published by Brayan K

Memory management in JavaScript is the automatic process by which the engine allocates memory for your variables and objects, then frees it through garbage collection once that data is no longer reachable.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Reachability determines eligibility, not an exact collection time

JavaScript manages allocation and garbage collection, but “no longer needed by my feature” is not the same as “unreachable by the runtime.” Unreachable objects may be collected; this lesson does not promise when collection occurs or that process memory immediately falls. The examples inspect references and explicit resource cleanup, not heap addresses, byte counts or finalizer timing.

let record = { title: "Draft", visits: 1 };
const retained = [record]; // The array holds the same object.
record.visits++;
record = null; // Remove only this binding's reference.
console.log(record);
console.log(retained[0].title, retained[0].visits);
retained.length = 0; // Remove this array's entry too.
console.log(retained.length);

// ✅ Expected output:
// null
// Draft 2
// 0

The first assignment to null does not destroy the object: retained still reaches it. Clearing the array removes that particular route. The printed zero establishes the array’s state, not that a garbage collector has already reclaimed physical memory.

Follow closure bindings rather than treating every closure as a leak

function keep(target) { return () => target.title; }
let record = { title: "Draft" };
const read = keep(record);
record = null;
console.log(read());

// ✅ Expected output:
// Draft
let record = { title: "Draft" };
const read = () => record;
record = null;
console.log(read());

// ✅ Expected output:
// null

These are different bindings. A closure is not automatically a leak: retaining its data can be exactly what the feature needs. It becomes an unwanted retention problem when the feature has finished but a long-lived owner still keeps the closure or its reachable data. Closures and Scope owns binding behaviour; Advanced Scope, Closures & Lexical Environments owns pending-work and closure-lifecycle patterns.

function createHandle(value) {
  let retained = value;
  return {
    read() { return retained; },
    release() { retained = null; }
  };
}
let source = { title: "Draft" };
const handle = createHandle(source);
console.log(handle.read() === source);
handle.release();
console.log(handle.read());
console.log(source.title);
source = null;

// ✅ Expected output:
// true
// null
// Draft

release changes the handle’s binding. The caller’s source is still a separate reference until it is reassigned. An API can control the references it owns; it cannot erase every reference held elsewhere.

Cycles and global ownership are different questions

let first = { name: "A" };
let second = { name: "B" };
first.next = second;
second.next = first;
const roots = [first];
first = null;
second = null;
console.log(roots[0].next.name);
console.log(roots[0].next.next === roots[0]);
roots.length = 0;
console.log(roots.length);

// ✅ Expected output:
// B
// true
// 0

A cycle alone does not make modern tracing garbage collectors unable to reclaim objects. Reachability from roots matters. Here roots keeps the cycle reachable; clearing it removes that demonstrated route. The example does not observe collection afterward.

Language semantics do not require every primitive to live on a physical stack or every object to be represented by a raw address exposed to JavaScript. Engines can optimize storage. V8’s published collector designs describe an implementation, not a permanent three-region rule shared by every JavaScript host.

Stop resources at the feature’s lifecycle boundary

const target = new EventTarget();
const calls = [];
function mount(label) {
  const listener = () => calls.push(label);
  target.addEventListener("update", listener);
  return () => target.removeEventListener("update", listener);
}
const dispose = mount("panel");
target.dispatchEvent(new Event("update"));
dispose();
dispose();
target.dispatchEvent(new Event("update"));
console.log(calls.join(","));

// ✅ Expected output:
// panel

The target no longer invokes that listener after disposal. Holding the returned disposer can still retain variables referenced by that function, so remove unused owner handles too. Events owns listener identity and options; this fixture checks when the feature releases its registration.

let ran = false;
const timer = setTimeout(() => { ran = true; }, 0);
clearTimeout(timer);
await new Promise(resolve => setTimeout(resolve, 0));
console.log(ran);

// ✅ Expected output:
// false

A timer or interval is a resource to stop explicitly when it is no longer needed. The handle is not printed because its representation differs by host. A pending network operation, observer or subscription similarly needs its own supported disposal mechanism; nulling a local variable is not that mechanism. AbortController & Cancelling Async Work owns cooperative abort signals.

Bound caches by a stated policy

const cache = new Map();
function remember(key, value) {
  if (!cache.has(key) && cache.size === 2) cache.delete(cache.keys().next().value);
  cache.set(key, value);
}
remember("A", { value: 1 });
remember("B", { value: 2 });
remember("A", { value: 3 });
remember("C", { value: 4 });
console.log([...cache.keys()].join(","));
console.log(cache.size, cache.has("A"));

// ✅ Expected output:
// B,C
// 2 false

Updating A does not move its insertion position, so this is FIFO eviction rather than least-recently-used eviction. The cache holds at most two entries; it does not establish a bound on the bytes reachable from large keys or values. Map & Set owns collection semantics.

Weak collections do not provide deterministic disposal

const metadata = new WeakMap();
const key = { id: "panel" };
metadata.set(key, { selected: true });
console.log(metadata.has(key), metadata.get(key).selected);
console.log(metadata.has({ id: "panel" }));
console.log(typeof metadata.size, typeof metadata.keys);
metadata.delete(key);
console.log(metadata.has(key));

// ✅ Expected output:
// true true
// false
// undefined undefined
// false

The object key is matched by identity, and this example keeps a strong reference to it throughout. It deliberately does not claim to observe garbage collection. WeakMap does not offer an enumerable key list or size, because collection-dependent contents should not become a timing signal through those APIs.

const metadata = new WeakMap();
metadata.set("panel", { selected: true });

// ✅ Expected error:
// TypeError: Invalid value used as weak map key

Use a Map when keys are strings and you need explicit enumeration and eviction. A WeakMap can associate metadata with an object without making the key strongly reachable merely through that association, but it does not close sockets, remove listeners or replace a feature’s dispose method.

FinalizationRegistry callbacks may run later or may not run at all. Do not make correctness depend on one closing a resource, decrementing a counter or sending a final message. WeakRef also cannot turn an application’s required data into reliably available data; both require careful optional-use contracts.

Measure retention with a repeatable lifecycle, not one large number

In a browser project, take a baseline heap snapshot, repeat a feature’s mount/use/unmount cycle, then compare another snapshot. Inspect objects that remain and their retaining paths. Distinguish the object’s own allocation from the larger graph it keeps reachable. Developer tools and console inspection can themselves retain objects, so avoid drawing conclusions from a single retained console result.

A rising high-water mark or garbage-collection sawtooth is not by itself proof of a leak. Repeated unwanted retention after equivalent cleanup is evidence worth investigating. This lesson’s code checks logical cleanup; it does not claim a byte-level leak test or prove a particular V8 generation, pause time or collector schedule.

Guided exercise: release the subscription you created

Fill the literal hints. Store the listener function, register that same function and remove it before the second event. The output should describe callback behaviour, not a collection event.

const target = new EventTarget();
let calls = 0;
const listener = () => { calls++; };
target.___("ping", listener); // 👉 replace ___ with addEventListener
target.dispatchEvent(new Event("ping"));
target.___("ping", listener); // 👉 replace ___ with removeEventListener
target.dispatchEvent(new Event("ping"));
console.log(___); // 👉 replace ___ with calls

// ✅ Expected output:
// 1

Independent brief: clean up every registered resource once

Implement createScope() with add(cleanup) and dispose(). add accepts a synchronous function while open, otherwise throws TypeError("cleanup must be a function") or Error("scope is closed"). dispose closes the scope before calling anything, detaches its cleanup list, and invokes callbacks in reverse registration order. Reentrant or repeated dispose calls do nothing.

Try every cleanup even if one fails. After all callbacks have been attempted, throw AggregateError(errors, "resource cleanup failed") if any failed, preserving the original reasons in the order encountered. Check reverse order, a failing middle callback, reentrant disposal, repeated disposal, invalid registration, and registration after close. The contract does not await asynchronous cleanup and makes no garbage-collection timing claim.

function createScope() {
  let closed = false;
  let cleanups = [];
  return {
    add(cleanup) {
      if (closed) throw new Error("scope is closed");
      if (typeof cleanup !== "function") throw new TypeError("cleanup must be a function");
      cleanups.push(cleanup);
    },
    dispose() {
      if (closed) return;
      closed = true;
      const pending = cleanups;
      cleanups = [];
      const errors = [];
      for (let index = pending.length - 1; index >= 0; index--) {
        try { pending[index](); } catch (error) { errors.push(error); }
      }
      if (errors.length) throw new AggregateError(errors, "resource cleanup failed");
    }
  };
}
const events = [];
const failure = new Error("middle failed");
const scope = createScope();
scope.add(() => events.push("first"));
scope.add(() => { events.push("middle"); throw failure; });
scope.add(() => { events.push("last"); scope.dispose(); });
try { scope.dispose(); }
catch (error) {
  console.log(error.name, error.message);
  console.log(error.errors.length, error.errors[0] === failure);
}
console.log(events.join(","));
scope.dispose();
console.log(events.join(","));
try { scope.add(() => {}); } catch (error) { console.log(error.message); }
const open = createScope();
try { open.add(null); } catch (error) { console.log(error.name, error.message); }
open.dispose();
open.dispose();

// ✅ Expected output:
// AggregateError resource cleanup failed
// 1 true
// last,middle,first
// last,middle,first
// scope is closed
// TypeError cleanup must be a function

Reference notes

The MDN memory-management guide explains reachability and weak associations. V8’s collector article describes that engine’s implementation. The heap-snapshot guide supports the inspection workflow, and the FinalizationRegistry reference states its scheduling limits.

Practice quiz

What does this complete program print? let value={name:"A"}; const other=value; value=null; console.log(other.name);

  • A
  • null
  • undefined
  • ReferenceError

Answer: A. The other reference still reaches the object.

What does this complete program print? function keep(value){return ()=>value.name} let value={name:"A"};const read=keep(value);value=null; console.log(read());

  • null
  • A
  • undefined
  • TypeError

Answer: A. The parameter binding captured by the returned function retains its own reference.

What does this complete program print? let value={name:"A"}; const read=()=>value; value=null; console.log(read());

  • A
  • undefined
  • null
  • TypeError

Answer: null. This closure reads the reassigned outer binding.

What does this complete program print? const key={};const map=new WeakMap([[key,7]]); console.log(map.has(key),map.has({}));

  • true true
  • false false
  • false true
  • true false

Answer: true false. WeakMap object keys use identity.

What does this complete program print? const map=new WeakMap(); console.log(typeof map.size,typeof map.keys);

  • undefined undefined
  • number function
  • number undefined
  • undefined function

Answer: undefined undefined. WeakMap has neither a size property nor key enumeration.

What does this complete program print? const map=new Map([["A",1],["B",2]]); map.set("A",3); console.log([...map.keys()].join(","));

  • B,A
  • A,B
  • A,A,B
  • A

Answer: A,B. Updating an existing Map value does not move its insertion position.

What does this complete program print? const target=new EventTarget();let calls=0; const fn=()=>calls++; target.addEventListener("x",fn); target.removeEventListener("x",fn); target.dispatchEvent(new Event("x")); console.log(calls);

  • 1
  • 2
  • 0
  • undefined

Answer: 0. Removing the actual registered listener prevents that later invocation.

What does this complete program print? const actions=[()=> "first",()=> "second",()=> "third"]; const order=[]; for(let index=actions.length-1;index>=0;index--)order.push(actions[index]()); console.log(order.join(","));

  • first,second,third
  • second,third,first
  • third,first,second
  • third,second,first

Answer: third,second,first. Reverse registration order runs the most recently added cleanup first.

Continue this course

Related lessons