typestar

Deep clone in JavaScript

Copies a nested structure so that changing the copy leaves the original alone.

function deepClone(value) {
  if (value === null || typeof value !== "object") return value;
  if (Array.isArray(value)) return value.map(deepClone);
  const out = {};
  for (const key of Object.keys(value)) {
    out[key] = deepClone(value[key]);
  }
  return out;
}

Keywords and builtins used here

The run, in numbers

Lines
9
Characters to type
251
Tokens
74
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 8 of 8 in Objects & collections, step 34 of 43 in Language basics.

← Previous Next →