How to detect circular references?

QuestionsQuestions8 SkillsProStringify Circular JSONSep, 02 2025
0163

To detect circular references in a JavaScript object, you can use a WeakSet to keep track of objects that have already been seen during traversal. Here's a simple function to demonstrate this:

const hasCircularReference = (obj) => {
  const seen = new WeakSet();

  const detect = (value) => {
    if (value !== null && typeof value === "object") {
      if (seen.has(value)) {
        return true; // Circular reference detected
      }
      seen.add(value);
      for (const key in value) {
        if (detect(value[key])) {
          return true; // Circular reference found in nested objects
        }
      }
    }
    return false; // No circular reference
  };

  return detect(obj);
};

// Example usage:
const objA = {};
const objB = {};
objA.ref = objB;
objB.ref = objA; // Circular reference

console.log(hasCircularReference(objA)); // Outputs: true

Explanation:

  1. WeakSet: A WeakSet is used to store objects that have been encountered.
  2. Recursive Function: The detect function checks each property of the object. If it finds an object that has already been seen, it returns true, indicating a circular reference.
  3. Traversal: The function recursively checks nested objects.

This method is efficient and prevents memory leaks since WeakSet does not prevent garbage collection of its entries. If you want to explore more about this topic, consider checking out relevant labs on LabEx!

0 Comments

no data
Be the first to share your comment!