CrackFrontendCF
Resources
Practice
CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna

CrackFrontendCF
Resources
Practice

πŸ”„ Removing Circular References from Objects

Removes circular references from object graphs using WeakSet tracking. Prevents JSON.stringify errors and infinite recursion.

Circular references can create serious problems in JavaScript β€” from infinite recursions to errors. Here’s how to remove cycles both structurally and during serialization using idiomatic, memory-safe JavaScript. -- πŸ” 1. Structural Removal with Purpose: Remove circular references in-place from object graphs (e.g., linked lists, trees, graphs). How It Works: A recursive traversal tracks visited objects using a . If a reference is encountered again, it is removed. Code: Test Case: -- 🧡 2. Serialization-Safe: with Replacer Purpose: Remove cycles on-the-fly during serialization to JSON. Useful when you don't want to mutate the original object. How It Works: accepts a replacer function. You can use a inside this replacer to track seen objects and return for repeats (i.e., remove cycles). Code: Usage: Output: -- πŸ” When to Use Which? Use βœ… Yes ❌ No βœ… Yes βœ… Uses WeakSet -- 🧠 Key Insight is perfect for tracking object identity in cyclic graphs, without interfering with garbage collection. -- βœ… Final Take Use structural traversal to clean up in-memory object graphs. Use with a custom replacer to safely serialize cyclic structures on-demand. These patterns are standard in tools like , , or serializers for distributed systems and state management frameworks. -- <!-quiz-start --Q1: Why is used instead of a regular for tracking visited objects? [ ] WeakSet is faster [ ] WeakSet can store primitives [x] WeakSet allows garbage collection of objects when no other references exist [ ] WeakSet supports iteration Q2: What does do when it detects a circular reference? [ ] Throws an error [ ] Returns undefined [x] Deletes the property that creates the cycle [ ] Replaces the reference with null Q3: When should you use with JSON.stringify instead of ? [x] When you want to serialize without mutating the original object [ ] When you need better performance [ ] When dealing with arrays only [ ] When the object has no circular references <!-quiz-end --
JavaScriptUtilities
βž• Chained Sum (Curried Function)
medium
⏱️ Debounce Function in JavaScript
medium
πŸ“‹ Deep Clone Implementation
easy
πŸ”„ distinctUntilChanged() Polyfill
easy
πŸ“„ Document Comparison (Diff)
easy
πŸ“’ Custom EventEmitter Implementation
hard
πŸ“¦ Flatten Object Implementation
medium
🐫➑️🐍 Converting camelCase to snake_case in JavaScript (Without Regex)
easy
πŸ”„ mapLimit: Controlled Concurrency in JavaScript
medium
⚑️ Fire on Push: Dispatching Custom Events When an Array Changes in JavaScript
medium
πŸ”„ Removing Circular References from Objects
hard
πŸ“Š Sampling Function: Execute Once Every N Calls
medium
⏱️ Throttle Function in JavaScript
medium
πŸ”„ undefinedToNull Utility
medium
11 of 14
LibraryJavaScriptUtilities58 of 61

πŸ”„ Removing Circular References from Objects

jsutilshard

Circular references can create serious problems in JavaScript β€” from infinite recursions to JSON.stringify errors. Here’s how to remove cycles both structurally and during serialization using idiomatic, memory-safe JavaScript.


πŸ” 1. Structural Removal with WeakSet

Purpose:

Remove circular references in-place from object graphs (e.g., linked lists, trees, graphs).

How It Works:

A recursive traversal tracks visited objects using a WeakSet. If a reference is encountered again, it is removed.

Code:

const removeCycle = (obj) => {
  const set = new WeakSet([obj]);

  (function iterate(current) {
    for (let key in current) {
      if (!current.hasOwnProperty(key)) continue;

      const val = current[key];

      if (typeof val === 'object' && val !== null) {
        if (set.has(val)) {
          delete current[key]; // Cycle detected, remove
        } else {
          set.add(val);
          iterate(val); // Recurse deeper
        }
      }
    }
  })(obj);
};

Test Case:

function List(val) {
  this.val = val;
  this.next = null;
}

const item1 = new List(10);
const item2 = new List(20);
const item3 = new List(30);

item1.next = item2;
item2.next = item3;
item3.next = item1; // Circular reference

removeCycle(item1);

console.log(item1);
// { val: 10, next: { val: 20, next: { val: 30 } } }

🧡 2. Serialization-Safe: JSON.stringify() with Replacer

Purpose:

Remove cycles on-the-fly during serialization to JSON. Useful when you don't want to mutate the original object.

How It Works:

JSON.stringify accepts a replacer function. You can use a WeakSet inside this replacer to track seen objects and return undefined for repeats (i.e., remove cycles).

Code:

const getCircularReplacer = () => {
  const seen = new WeakSet();
  return (key, value) => {
    if (typeof value === 'object' && value !== null) {
      if (seen.has(value)) return; // Omit cyclic reference
      seen.add(value);
    }
    return value;
  };
};

Usage:

console.log(JSON.stringify(item1, getCircularReplacer(), 2));

Output:

{
  "val": 10,
  "next": {
    "val": 20,
    "next": {
      "val": 30
    }
  }
}

πŸ” When to Use Which?

Use CaseUse removeCycle()Use getCircularReplacer()
Mutate structure and clean cyclesβœ… Yes❌ No (non-destructive)
Safe JSON serialization❌ Noβœ… Yes
Need to traverse or clone afterwardβœ… Yes❌ No (only during serialization)
Want GC-safe memory trackingβœ… Uses WeakSetβœ… Uses WeakSet

🧠 Key Insight

WeakSet is perfect for tracking object identity in cyclic graphs, without interfering with garbage collection.


βœ… Final Take

  • Use structural traversal + WeakSet to clean up in-memory object graphs.
  • Use JSON.stringify with a custom replacer to safely serialize cyclic structures on-demand.

These patterns are standard in tools like fast-safe-stringify, circular-json, or serializers for distributed systems and state management frameworks.


Quick Quiz

Test your understanding with 3 quick questions

Q1Why is `WeakSet` used instead of a regular `Set` for tracking visited objects?
Q2What does `removeCycle` do when it detects a circular reference?
Q3When should you use `getCircularReplacer()` with JSON.stringify instead of `removeCycle()`?

Continue Reading

CrackFrontend

Your guide to mastering frontend interviews

Resources

LibraryPracticeDonate

Company

About UsContact

Legal

Privacy PolicyTerms of Service

Built with ❀️ by Tushar Khanna