Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
JavaScript

JavaScript: Use structuredClone() for True Deep Copy of Objects

- 29.05.26 - ErcanOPAK

πŸ“¦ Finally, True Deep Copy Without Libraries

JSON.parse(JSON.stringify()) fails with dates, undefined, functions. structuredClone() handles dates, maps, sets, arrays, nested objects β€” everything.

❌ JSON Hack (Broken)

const obj = {
  date: new Date(),
  fn: () => {},
  undef: undefined
};

const copy = JSON.parse(JSON.stringify(obj));
// date becomes string!
// fn and undef are gone!
console.log(copy);
// { date: "2024-01-01T00:00:00.000Z" }

βœ… structuredClone (Perfect)

const obj = {
  date: new Date(),
  map: new Map([[1, 'one']]),
  arr: [1, [2, 3]]
};

const copy = structuredClone(obj);
// date is Date object!
// map is Map object!
// nested arrays preserved!
copy.arr[1][0] = 99;
console.log(obj.arr[1][0]); // 2 (original unchanged)

🎯 What structuredClone Supports

// Primitives (string, number, boolean, null)
const copy = structuredClone('hello');

// Arrays (nested works)
const arr = [1, [2, [3]]];
const arrCopy = structuredClone(arr);

// Objects (nested works)
const obj = { a: { b: { c: 1 } } };
const objCopy = structuredClone(obj);

// Dates
const date = new Date();
const dateCopy = structuredClone(date);
dateCopy.setFullYear(2025);
console.log(date.getFullYear()); // 2024 (unchanged)

// Maps
const map = new Map([['key', 'value']]);
const mapCopy = structuredClone(map);

// Sets
const set = new Set([1, 2, 3]);
const setCopy = structuredClone(set);

// ArrayBuffers, TypedArrays
const buffer = new ArrayBuffer(8);
const bufferCopy = structuredClone(buffer);

βœ… Real-World Use Case

// React/Redux state updates
const initialState = {
  user: { name: 'Alice', preferences: new Map([['theme', 'dark']]) },
  lastLogin: new Date()
};

// ❌ Before structuredClone
const newState = JSON.parse(JSON.stringify(initialState));
// lastLogin is string, preferences gone

// βœ… After structuredClone
const newState = structuredClone(initialState);
newState.user.name = 'Bob';
// original state unchanged, all types preserved

// Form state copy (before user edits)
const originalFormData = getFormData();
const workingCopy = structuredClone(originalFormData);
// Edit workingCopy, compare with original to detect changes

πŸ’‘ Limitations

  • Does NOT copy functions (throws error)
  • Does NOT copy DOM nodes (throws error)
  • Does NOT copy Symbols (ignores them)
  • Does NOT copy prototypes (plain objects only)
  • Circular references are supported (works fine)

“Lost Date objects in Redux because JSON.stringify turned them into strings. Months of debugging. structuredClone fixed everything in one line. Native solution, no libraries.”

β€” React Developer

Related posts:

How to get session value in Javascript

Ajax Requests Succeed but UI Never Updates

JS β€œawait” Inside forEach Is a Bug

Post Views: 5

Post navigation

HTML: Use Download Attribute to Force File Download Instead of Opening
Ajax: Use Navigator.sendBeacon() for Reliable Analytics on Page Unload

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

June 2026
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  
« May    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (805)
  • Add Constraint to SQL Table to ensure email contains @ (580)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (579)
  • Average of all values in a column that are not zero in SQL (538)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (505)
  • Find numbers with more than two decimal places in SQL (454)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files
  • Ajax: Add Custom Headers to Fetch Requests
  • JavaScript: Use console.table to Display Arrays as Tables
  • HTML: Use Spellcheck Attribute to Enable Browser Spell Check
  • CSS: Use user-select to Prevent Text Selection
  • Windows 11: Use Snipping Tool for Instant Screenshots

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (953)
  • How to add default value for Entity Framework migrations for DateTime and Bool (882)
  • Get the First and Last Word from a String or Sentence in SQL (838)
  • How to select distinct rows in a datatable in C# (808)
  • How to make theater mode the default for Youtube (805)

Recent Posts

  • C#: Use String Interpolation Instead of Concatenation
  • C#: Use Tuples to Return Multiple Values from Methods
  • SQL: Use ISNULL and NULLIF for Smart NULL Handling
  • .NET Core: Use Data Annotations for Model Validation
  • Git: Use Git Clean to Remove Untracked Files

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com