JavaScript Objects
Objects are the foundation of JavaScript. Understanding how to work with them effectively is essential for writing quality code.Understanding Object Mutability
JavaScript’s primitive data types are immutable, meaning their value cannot change once created. However, objects and arrays are mutable, allowing their value to be altered after creation. What this means in practice is that primitives are passed by value, whereas objects and arrays are passed by reference.objCopy. Changing one of the variables will affect the other one, as they both reference the same object.
Shallow Cloning
Using the spread operator (...) or Object.assign(), we can clone the object and create a new one from its properties.
Using Spread Operator
Using Object.assign()
Deep Cloning
In order to create a deep clone of an object, we need to recursively clone every nested object, cloning nested objects and arrays along the way.Manual Deep Clone Implementation
Starting with the edge cases, we need to check if the passed object isnull and, if so, return null. Otherwise, we can use Object.assign() and an empty object ({}) to create a shallow clone of the original.
This code snippet is designed specifically with plain objects and arrays in mind. It can’t handle class instances, functions, and other special cases.
Deep Cloning with structuredClone()
JavaScript introduced thestructuredClone() global function, which can be used to deep clone objects. Instead of implementing a complicated recursive function, we can simply use this function to clone the object.
When to Use Each Method
Shallow Clone - Spread Operator
Shallow Clone - Spread Operator
Use
{ ...obj } when:- You only need to clone the top level
- The object doesn’t have nested objects
- You need readable, concise code
Shallow Clone - Object.assign()
Shallow Clone - Object.assign()
Use
Object.assign({}, obj) when:- You need to merge multiple objects
- You want to be explicit about cloning
- Compatibility with older code
Deep Clone - structuredClone()
Deep Clone - structuredClone()
Use
structuredClone(obj) when:- You need to clone nested objects/arrays
- You want the best performance
- You need to clone complex structures like Sets, Maps, Dates
Deep Clone - Custom Implementation
Deep Clone - Custom Implementation
Use a custom
deepClone() when:- You need to support older environments
- You need custom cloning logic
- You need to handle special cases