afyonkarahisarkitapfuari.com

Mastering JavaScript Object Cloning with structuredClone()

Written on

Understanding the Need for Cloning in JavaScript

Recently, I came across an insightful piece by Flavio Copes, a well-known source of valuable programming knowledge. He discussed a swift and effective way to duplicate objects in JavaScript using the structuredClone() method. While I may have revealed the conclusion too soon, let's delve into the topic step by step.

The challenge arises when dealing with variables in JavaScript. Primitive types, such as strings, numbers, and booleans, are straightforward since they are passed by value. However, complications occur with objects, arrays, and dates because they are passed by reference. This means that altering an object also modifies the original instance.

For clarity, consider this example:

const a = { name: "John" };

const b = a;

b.name = "Jane";

console.log(a.name); // Jane

In contrast, when using a primitive variable:

const a = "John";

const b = a;

b = "Jane";

console.log(a); // John

When we need to create a copy of an object, we must employ different techniques. Several methods are commonly recommended.

Using the Spread Operator

We can utilize the spread operator (...) to generate a new object that mirrors the properties and values of the original. However, this approach only creates a shallow copy, meaning that if the original object contains nested objects, the new object will still reference those nested structures. Here’s an illustration:

const a = { name: "John", age: 30 };

const b = { ...a };

b.name = "Jane";

console.log(a.name); // John

For deeper structures:

const c = { name: "John", age: 30, address: { city: "Rome" } };

const d = { ...c };

d.address.city = "Milan";

console.log(c.address.city); // Milan

Object.assign() Method

Another option is the Object.assign() method, which works similarly to the spread operator but can be a bit more complex. It also retains references for nested objects, as demonstrated below:

const a = { name: "John", age: 30 };

const b = Object.assign({}, a);

b.name = "Jane";

console.log(a.name); // John

For nested properties:

const c = { name: "John", age: 30, address: { city: "Rome" } };

const d = Object.assign({}, c);

d.address.city = "Milan";

console.log(c.address.city); // Milan

Using JSON Methods

To tackle this issue, we previously relied on a combination of methods. By using JSON.stringify() to convert the object into a JSON string, and then JSON.parse() to convert it back into an object, we could achieve a deep copy. For example:

const a = { name: "John", age: 30 };

const b = JSON.parse(JSON.stringify(a));

b.name = "Jane";

console.log(a.name); // John

For nested structures:

const c = { name: "John", age: 30, address: { city: "Rome" } };

const d = JSON.parse(JSON.stringify(c));

d.address.city = "Milan";

console.log(c.address.city); // Rome

While effective, this method can be relatively slow.

Introducing structuredClone()

This is where the structuredClone() method becomes invaluable. Its syntax is straightforward:

structuredClone(value);

structuredClone(value, options);

Its application is even simpler:

const a = { name: "John", age: 30 };

const b = structuredClone(a);

b.name = "Jane";

console.log(a.name); // John

For nested structures:

const c = { name: "John", age: 30, address: { city: "Rome" } };

const d = structuredClone(c);

d.address.city = "Milan";

console.log(c.address.city); // Rome

In conclusion, the most efficient method for duplicating an object in JavaScript is undoubtedly the structuredClone() method. Thank you for reading! Stay tuned for more insights. Subscribe to my Medium email list to catch my next article.

This video demonstrates how to effectively deep clone objects in JavaScript using the structuredClone method.

In this video, learn about deep copying objects in JavaScript and the different methods available for achieving this.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Understanding the Human Element in Scientific Inquiry

This exploration highlights the human aspect of science, emphasizing how personal biases and community processes shape scientific inquiry.

Unlocking Effective Procurement Strategies for Finance Tech

Discover insights on finance technology procurement strategies, key challenges, and expert advice from industry leaders.

# The Key to Effective Weight Loss: A Fresh Perspective

Discover a transformative approach to weight loss that prioritizes fitness and well-being over traditional dieting methods.

Title: Combatting Aging: The Role of Zombie Cells and Exercise

Explore how exercise combats senescent cells, the

# Reflecting on NaPoWriMo: Embracing Impermanence and Creativity

A reflective piece on NaPoWriMo, celebrating creativity through prompts and the beauty of impermanence.

Overcoming Challenges Without Succumbing to Pessimism

Learn how to navigate obstacles in your pursuit of goals without falling into pessimism and discouragement.

Embracing Agelessness: The Inner Self Beyond Time

Explore the concept of inner agelessness and the transformative power of mindfulness practices in our later years.

# Trust as the New Competitive Edge in Modern Business

In today's market, trust is the crucial factor that drives business success, surpassing traditional competitive strategies.