Mastering Deep vs Shallow Cloning in JavaScript and jQuery
This article explains the difference between deep and shallow cloning in JavaScript, illustrates how reference types affect object copies, demonstrates practical implementations using loops, Array.concat, and jQuery.extend, and shows visual examples to help developers avoid common pitfalls when merging objects.
While reviewing frontend concepts, the author discovered that many topics are interconnected, such as examining jQuery's
extendsource code, which leads to a deeper look at cloning techniques.
What Is Deep Clone?
JavaScript has six basic data types: five primitive types (string, number, undefined, boolean, null) stored on the stack, and one complex reference type (object, including functions, arrays, objects) stored as a pointer on the heap. Deep cloning means copying all properties of an object to a new memory location so that changes to the new object do not affect the original.
Shallow Clone
Shallow cloning simply copies the object. If a property holds a reference value, the new object’s property points to the same memory address, so modifications affect both objects. Primitive values like
nameare copied by value and do not cause side effects.
Implementing Deep Clone
A typical approach uses a
for‑inloop to iterate over all properties, checks whether a property is a reference, and recursively clones it until every property is a primitive value. The result is a completely independent object.
Additional Tools
Array.concat creates a new array and can be used for shallow cloning of arrays.
<code>var a = [1,2,3];
console.log(a.concat(4,5)); // [1,2,3,4,5]
console.log(a); // [1,2,3]
</code>jQuery.extend([deep], target, object1 [, objectN]) merges objects. The optional
deepboolean determines whether the merge is recursive (deep copy) or shallow.
deep (Boolean) – If true, perform a recursive (deep) copy; default false for shallow copy. target (Object) – The object that receives new properties. object1 (Object) – An object whose properties are merged into the target. objectN (Object) – Additional objects to merge.
Examples of merging two objects show that when reference‑type properties are present, both objects may point to the same nested object, causing changes in one to affect the other. Using deep cloning prevents this issue, while shallow merging simply overwrites properties.
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.