Sometimes there is a task in JavaScript to clone some object. And at this point it is not always clear how it should be done correctly.

The solution is

We have an object that we want to clone. That is, we want to take all the properties of that object and transfer them to the new object.

let obj22 = {s:123, z:456}

Now we need to create a new binding identifier and assign it the result of a literal object declaration expression and a triplet operator.

Production of ObjectLiteral by ECMAScript standard

let obj33 = {…obj22}

From this point on there are already two objects and two references to them living in RAM. The cloning was successful.

Let’s change their properties and make sure everything is correctly declined.

obj22.x = 111
obj33.r = 777

The original object stores its properties, and the cloned object stores its properties. The addition of new properties occurred only for each of the objects.

0 Shares:
Leave a Reply

Your email address will not be published.

You May Also Like