JavaScript troubleshooting — structuredClone is not defined

Uncaught ReferenceError: StructuredClone is not defined

The error is because structuredClone() is not supported in the browser. For example, structuredClone() is not supported on Safari iOS until v15.4(Released in 2022) and it is not supported on IE at all.

To add compatible structuredClone() support in all browsers, you can define a manual deep copy function or use an existing one of a JavaScript library, like copyDeep of Lodash, clone() of Ramda.

Solution 1 — use user defined deep copy function

A user-defined deep copy function which is compatible with IE browser:

if (!window.structuredClone) {
    function myDeepCopy(value) {
        if (Array.isArray(value)) {
            var count = value.length;
            var arr = new Array(count);
            for (var i = 0; i < count; i++) {
                arr[i] = myDeepCopy(value[i]);
            }

            return arr;
        } else if (typeof value === 'object') {
            var obj = {};
            for (var prop in value) {
                obj[prop] = myDeepCopy(value[prop]);
            }

            return obj;
        } else { // Primitive value
            return value;
        }
    }

    window.structuredClone = myDeepCopy;
}

Solution 2 — use cloneDeep() of Lodash

Lodash is a modern JavaScript utility library. It is released under the MIT license & supports modern environments.

cloneDeep(value) creates a deep clone of value.

Example (Use lodash as a ES6 module):

// In ES6 module style:
import _ from 'lodash';
// Or you can just import the function you need
// import cloneDeep from "lodash/cloneDeep";

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false

Further reading

Reference