🟒 EasyFix the CodeπŸ› Debug Challenge

Deep clone breaks with JSON.stringify

Buggy Code β€” Can you spot the issue?

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

Fixed Code

// 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 Explained

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.

More Fix the Code Debug Challenges

🟑 Mediumthis lost in event listenerβ†’πŸŸ‘ MediumObject mutation in array mapβ†’πŸ”΄ HardPrototype pollution vulnerabilityβ†’πŸŸ‘ MediumProxy trap modifies original object directlyβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab