# unicorn/prefer-structured-clone

> Require `structuredClone()` for deep clones

`JSON.parse(JSON.stringify(value))` turns a `Date` into a string, drops `undefined`, turns a `Map` or `Set` into `{}`, and throws on an object that refers to itself. `structuredClone()` is built in and copies all of these correctly, so you don't need a library function such as lodash's `cloneDeep` either.

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-structured-clone" = "error" # or "warn"
```

Every option, set to its default:

```toml bunfig.toml
[lint.rules]
"unicorn/prefer-structured-clone" = ["error", {
  functions = ["cloneDeep", "utils.clone"],
}]
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad {"count": 2} */}
```js
const draft = JSON.parse(JSON.stringify(settings));
const backup = _.cloneDeep(settings);
```

Not reported:

{/* good */}
```js
const draft = structuredClone(settings);
```

## Options

| Option | Default | What it does |
| --- | --- | --- |
| `functions` | `["cloneDeep", "utils.clone"]` | Names of functions to report. The list replaces the default. |

A name with a dot, such as `utils.clone`, only matches that object and method. A name without a dot matches a call to that function, and a method with that name on any object.

{/* bad {"options": [{"functions": ["deepCopy"]}]} */}
```js
const draft = deepCopy(settings);
```

{/* good {"options": [{"functions": ["deepCopy"]}]} */}
```js
const backup = _.cloneDeep(settings);
```

## When not to use it

`structuredClone()` throws on functions and DOM nodes, and the copy of a class instance is a plain object. If you clone values like that, keep your own function.
