Middle+
Among the listed methods of copying an object, which support cyclic references?
sobes.tech AI
Answer from AI
Cyclic references occur when an object refers to itself directly or through a chain of references.
Among the methods of copying objects in JavaScript:
- Shallow copy — does not support cycles, as it simply copies references.
- Deep copy via JSON.parse(JSON.stringify(obj)) — does not support cycles, will throw an error or result in an infinite loop.
- Recursive deep copy with tracking of visited objects — supports cycles if a mechanism to track already copied objects (e.g., using WeakMap) is implemented.
- Using specialized libraries (lodash.cloneDeep) — supports cycles, as it internally implements a mechanism to track cyclic references.
Example implementation with WeakMap:
function deepClone(obj, hash = new WeakMap()) {
if (obj === null || typeof obj !== 'object') return obj;
if (hash.has(obj)) return hash.get(obj);
const clone = Array.isArray(obj) ? [] : {};
hash.set(obj, clone);
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = deepClone(obj[key], hash);
}
}
return clone;
}
Thus, only deep copy methods with tracking of already processed objects support cyclic references.