Skip to content

Circular Reference

Quick summary

An object points to itself (directly or through a chain), causing JSON.stringify or traversal to fail or loop forever.

Why this happens

  • An object property references the object itself

  • Two objects reference each other (A → B → A)

  • A linked list or tree has a cycle in its pointers

Minimal example

✗ Broken code
const obj = { name: 'Alice' };
obj.self = obj; // Circular reference!
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
✓ Fixed code
const obj = { name: 'Alice' };
// Don't create circular reference
// or use a replacer:
const seen = new WeakSet();
const safe = JSON.stringify(obj, (key, val) => {
  if (typeof val === 'object' && val !== null) {
    if (seen.has(val)) return '[Circular]';
    seen.add(val);
  }
  return val;
});

obj.self = obj creates a cycle: obj → self → obj → self → ... JSON.stringify cannot serialize this. Removing the self-reference or using a replacer that detects cycles fixes it.

How to diagnose

  • Look for 'Converting circular structure to JSON' errors

  • Inspect the object to find self-referential properties

  • Check if traversal algorithms loop forever

How to fix

  • Break the cycle by removing or nulling the circular reference

  • Use a replacer function in JSON.stringify to skip circular properties

  • Use a Set to track visited objects during traversal

How to prevent

  • Avoid self-references unless using a structure designed for them

  • Use libraries that handle circular references in serialization

Related Resources

Related Glossary

Related Lessons

  • Objects

    Learn about object references.

← Back to language