Write a function to check if an object has a circular reference.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
Traverse the object graph and keep track of objects already visited during the traversal. If you encounter an object that has already been visited in the current path, you have found a cycle.
1. Use a Set or a WeakSet to store visited objects.
2. Create a recursive helper function that takes the current object and the set of visited objects.
3. In the helper, add the current object to the set.
4. Iterate through the properties. If a property's value is an object and has already been seen in the set, return true.
5. If not, recursively call the helper on that property's value.
function hasCircularReference(obj) {
const visited = new Set();
function traverse(current) {
if (current === null || typeof current !== 'object') {
return false;
}
if (visited.has(current)) {
return true; // Cycle detected
}
visited.add(current);
for (const key in current) {
if (Object.prototype.hasOwnProperty.call(current, key)) {
if (traverse(current[key])) {
return true;
}
}
}
// This is a simplified version. For a more robust solution, you might
// remove 'current' from 'visited' after checking its children to correctly
// handle separate branches of the object graph.
return false;
}
return traverse(obj);
}
const obj1 = { a: 1 };
obj1.b = obj1; // Circular reference
console.log(hasCircularReference(obj1)); // true
const obj2 = { a: 1, b: { c: 2 } };
console.log(hasCircularReference(obj2)); // false