Exercise 11: Deep Clone Object (without JSON)
Problem Statement
Create a function `deepClone(obj)` that deeply clones an object. Do not use JSON methods.
Example: deepClone({a: 1, b: {c: 2}}) → {a: 1, b: {c: 2}} (new object)
Sample Output:
deepClone({a: 1, b: {c: 2}}) => {a: 1, b: {c: 2}} (new object)
const obj = {x: 1}; const cloned = deepClone(obj); obj.x = 2; cloned.x => 1Solution
const deepClone = (obj) => {
if (obj === null || typeof obj !== "object") return obj;
if (obj instanceof Date) return new Date(obj.getTime());
if (obj instanceof Array) return obj.map(item => deepClone(item));
const cloned = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) cloned[key] = deepClone(obj[key]);
}
return cloned;
};Explanation
Overall Goal:
- Object ko completely clone karna (nested objects bhi).
- JSON methods avoid karna (functions, dates handle nahi karte).
Line 1: Function header
const deepClone = (obj) => {
Line 2: Primitive values
if (obj === null || typeof obj !== "object") return obj;- Primitives (string, number, boolean) directly return.
Line 3: Date handling
if (obj instanceof Date) return new Date(obj.getTime());- Date objects ko properly clone karna.
Line 4: Array handling
if (obj instanceof Array) return obj.map(item => deepClone(item));- Arrays ko recursively clone.
Line 5: Object clone
const cloned = {};- New empty object.
Line 6-7: Copy properties
for (const key in obj)→ har property iterate.if (obj.hasOwnProperty(key))→ own properties only.cloned[key] = deepClone(obj[key])→ recursively clone.
Real world:
- State management: immutable updates.
- Form data: draft copies.
- API responses: data manipulation without mutation.