How Can You Determine if Something Is a Deep Copy in JavaScript?

Shallow copies only duplicate the top-level structure of an object, while deep copies create new instances of all nested objects and their properties. By comparing the references of the nested objects (orig.nested === shallowCopy.nested and orig.nested === deepCopy.nested), we can determine whether a shallow or deep copy has been made.

const orig = {
  nested: {
    value: 1,
  },
};

const shallowCopy = { ...orig };
const deepCopy = {
  ...orig,
  nested: { ...orig.nested },
};

console.log(orig.nested === shallowCopy.nested); // true - not a deep copy
console.log(orig.nested === deepCopy.nested); // false - deep copy created

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda