How to copy an object in JavaScript?

Copy JavaScript object is a little tricky. We can do deep copy at the same time we can do the shallow copy. It depends on the requirements.

The deep copy of JavaScript objects can be done in different ways. Let’s consider the following JavaScript object:

Deep copy by JSON.parse/stringify with data loss:

We can use JSON.parse(JSON.stringify(obj)) if the object does not have following:

  • Dates,
  • functions,
  • undefined,
  • Infinity,
  • RegExps,
  • Maps,
  • Sets,
  • Blobs,
  • FileLists,
  • ImageDatas,
  • sparse Arrays,
  • Typed Arrays or
  • other complex types
// Example 
    const obj = {
        string: 'string',
        number: 123,
        bool: false,
        nul: null,
        getName: () => 'Joe Smith', // lost
        date: new Date(),  // string
        undef: undefined,  // lost
        inf: Infinity,  // forced to 'null'
        regex: /.*/,  // lost

    console.log(typeof;  //  object
    const clonedObj = JSON.parse(JSON.stringify(obj));
    console.log(typeof;  // String

Output of the cloned object

    // clonedObj looks like this: 
    clonedObj = {
        "string": "string",
        "number": 123,
        "bool": false,
        "nul": null,
        "date": "2021-08-29T02:29:37.997Z",
        "inf": null,
        "regex": {}