DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question
  1. Home
  2. Articles
  3. Frontend Engineering
  4. WeakMap and WeakRef: Memory-Efficient Data Structures
XLinkedInReddit
MediumFrontend Engineering

WeakMap and WeakRef: Memory-Efficient Data Structures

D
DevPrep Team
February 10, 2026·1 min read·0
Table of Contents
  • WeakMap vs Map
  • Use Case: Private Data
  • Use Case: DOM Metadata
  • WeakRef and FinalizationRegistry
  • Production Warning

Memory management is critical at Google scale. WeakMap and WeakRef are essential tools for avoiding memory leaks in long-running applications.

WeakMap vs Map

FeatureMapWeakMap
Key typesAnyObjects only
EnumerableYes (.keys(), .values())No
GC behaviorKeys prevent GCKeys are weakly held
Size propertyYesNo

Use Case: Private Data

const privateData = new WeakMap();

class User {
  constructor(name, ssn) {
    this.name = name;
    privateData.set(this, { ssn });
  }
  getSSN() {
    return privateData.get(this).ssn;
  }
}
// When User instance is GC'd, private data is too

Use Case: DOM Metadata

const elementData = new WeakMap();

function trackElement(el) {
  elementData.set(el, {
    clickCount: 0,
    firstSeen: Date.now()
  });
}
// When element is removed from DOM and GC'd,
// metadata is automatically cleaned up

WeakRef and FinalizationRegistry

WeakRef holds a weak reference to an object. FinalizationRegistry lets you run cleanup when an object is garbage collected.

const cache = new Map();
const registry = new FinalizationRegistry((key) => {
  cache.delete(key);
});

function cacheResult(key, value) {
  const ref = new WeakRef(value);
  cache.set(key, ref);
  registry.register(value, key);
}

function getCached(key) {
  const ref = cache.get(key);
  return ref?.deref(); // Returns undefined if GC'd
}

Production Warning

WeakRef and FinalizationRegistry are non-deterministic — you can't predict when GC runs. Never use them for critical logic. They're optimization tools, not correctness tools.

Related Articles

MediumFrontend Engineering

System Design #12: Design a Multi-Step Form Wizard

7 min read
MediumFrontend Engineering

Mastering Senior-Level JavaScript Interview Concepts

2 min read
MediumFrontend Engineering

System Design #9: Design a Collaborative Text Editor

9 min read

Comments (0)

Sign in to leave a comment.

No comments yet. Be the first to comment.

Table of Contents

  • WeakMap vs Map
  • Use Case: Private Data
  • Use Case: DOM Metadata
  • WeakRef and FinalizationRegistry
  • Production Warning

Series

View all Frontend Engineering articles →

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.