Sitemap
JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Member-only story

structuredClone(): The Easiest Way to Deep Clone Objects in JavaScript

5 min readMay 26, 2024

--

Press enter or click to view image in full size
Photo by Vladimir Fedotov on Unsplash

1.# Preface

Why hasn’t a native function been created in JavaScript until now to completely clone an object and all its contents, regardless of data type?

Oh, that’s an incredible thing, and it frustrates me and causes a lot of trouble in our work because we often need to deeply clone an object.

2.# 2 ways to deeply clone an object

My friend, do you know any ways to deep-clone an object? It would be best to clone these data types from the table above.

const testData = {
number: 123,
string: "test",
undefined: undefined,
null: null,
boolean: true,
object: { a: 1, b: { c: 2 } },
array: [1, 2, { d: 3 }],
function: function() { return "hello"; },
map: new Map([["key1", "value1"], ["key2", "value2"]]),
set: new Set([1, 2, 3]),
date: new Date(),
error: new Error("An error occurred"),
regex: /test/i,
domNode: document.createElement("div")
}

We will use testData as test data.

2.1# JSON.parse and JSON.stringify

--

--

fatfish
fatfish

Written by fatfish

Hi friends, I am a front-end engineer from Alibaba, let’s code happily together.

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.