menu
techminis

A naukri.com initiative

google-web-stories
Home

>

Programming News

>

Deep vs Sh...
source image

Medium

1M

read

359

img
dot

Image Credit: Medium

Deep vs Shallow Copy Behavior in JavaScript

  • When working with primitive types like numbers or strings, assigning a value results in a full copy being made in memory.
  • In contrast, when dealing with objects and arrays in JavaScript, they are treated as references rather than copied entirely.
  • Assigning an object or array to another variable copies the pointer to the data location, not the content itself.
  • Shallow copies only copy the top layer, meaning inner objects remain shared if they are objects themselves.
  • Tools like Object.assign and the spread syntax can be used to create shallow copies in JavaScript.
  • Deep copies duplicate every nested object or array inside, ensuring no shared references are left.
  • JSON.stringify and JSON.parse together can be used for simple deep copies, though not suitable for all data types.
  • Issues may arise with shallow copies when internal objects are inadvertently shared, leading to unexpected behavior.
  • JSON-based deep copying may lose data for functions, Date objects, Map, Set, BigInt, Symbol-keyed properties, or undefined values.
  • Handling cyclic structures in copying requires special consideration to avoid infinite loops and data loss.

Read Full Article

like

21 Likes

For uninterrupted reading, download the app