function deepClone(obj) { if (obj === null || typeof obj !== "object") { return obj; } const copy = Array.isArray(obj) ? [] : {}; for (const key in obj) { copy[key] = deepClone(obj[key]); } return copy; } const objA = { value: 1 }; const objB = { a: objA }; objA.b = objB; const clonedObj = deepClone(objA);
The bug is that the deepClone function does not handle circular references. When objA is cloned, objB is cloned as well, which in turn clones objA again, and so on. This results in an infinite loop. To fix this, you can keep track of the objects that have already been cloned using a Map, and check if an object has already been cloned before cloning it again.
function deepClone(obj, map = new Map()) { if (obj === null || typeof obj !== "object") { return obj; } if (map.has(obj)) { return map.get(obj); } const copy = Array.isArray(obj) ? [] : {}; map.set(obj, copy); for (const key in obj) { copy[key] = deepClone(obj[key], map); } return copy; } const objA = { value: 1 }; const objB = { a: objA }; objA.b = objB; const clonedObj = deepClone(objA);