Skip to content
JavaScript

Deep Clone

Deep clone objects, supporting common data types.

By EZ4Code Team
objectclonerecursion

Code

function deepClone(obj, hash = new WeakMap()) {
  if (obj === null || typeof obj !== "object") return obj;
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(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;
}

Explanation

Recursively clones all object properties, using WeakMap to resolve circular references.

More JavaScript Snippets