JavaScript Tips
How To Deep Clone Objects in JavaScript with Ease
Say goodbye to slow cloning with structuredClone() in JavaScript
A few days ago, I read an article by Flavio Copes (who is always a treasure trove of information). Flavio reports on a very rapid and powerful method for cloning anything in JavaScript: the structuredClone()
method. And in doing so, I spoiled the end of this post. But now let's take things in order and start from the beginning.
The beginning is the problem of using variables in JavaScript. When we use primitive variables (i.e. strings, numbers, booleans, etc.), we don’t have problems because they are passed by value.
But when we use objects, arrays, dates, anything, we have problems because they are passed by reference. And this means that if I modify an object, I also modify the original object.
To understand:
const a = { name: "John" };
const b = a;
b.name = "Jane";
console.log(a.name); // Jane
But with a primitive variable:
const a = "John";
const b = a;
b = "Jane";
console.log(a); // John
When we want to work with a copy of an object, we have to do something different. Some methods are usually recommended.