function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
const original = {
name: 'Alice',
born: new Date('1990-01-01'),
score: undefined,
greet: () => 'hello'
};
const clone = deepClone(original);
console.log(clone.born instanceof Date); // false! It's a string
console.log('score' in clone); // false! undefined dropped
console.log(clone.greet); // undefined! function dropped// Fix: Use structuredClone (modern, handles most types)
function deepClone(obj) {
return structuredClone(obj);
}
// structuredClone handles: Dates, Arrays, Maps, Sets, Blobs
// Still doesn't handle: functions, class instances, DOM nodes
// For functions too β use a recursive approach or lodash cloneDeep:
// import cloneDeep from 'lodash/cloneDeep';Bug: JSON.stringify drops undefined and functions, converts Dates to strings. The clone is incomplete.
Explanation: structuredClone is the modern built-in that handles Dates, Maps, Sets, etc. It still doesn't clone functions (they're not serializable) but handles most real-world cases.
Key Insight: JSON.parse/stringify is lossy. Use structuredClone() for modern deep cloning. Use lodash cloneDeep if you need to handle edge cases like functions.