← Back to Blog
Code Snippets August 13, 2026

JavaScript — Deep Object Comparison: Find Exactly What Changed

💻 CODE SNIPPET — Aug 13, 2026

JavaScript — Deep Object Comparison: Find Exactly What Changed

When you need to detect exactly which nested properties changed between two objects (config updates, state diffs, audit logs):

function deepDiff(obj1, obj2, path = '') {
  const diffs = [];
  const keys = new Set([...Object.keys(obj1), ...Object.keys(obj2)]);

  for (const key of keys) {
    const currentPath = path ? `${path}.${key}` : key;
    const a = obj1[key], b = obj2[key];

    if (a === undefined) diffs.push({ path: currentPath, type: 'added', value: b });
    else if (b === undefined) diffs.push({ path: currentPath, type: 'removed', value: a });
    else if (typeof a === 'object' && typeof b === 'object' && a !== null && b !== null)
      diffs.push(...deepDiff(a, b, currentPath));
    else if (a !== b) diffs.push({ path: currentPath, type: 'changed', old: a, new: b });
  }
  return diffs;
}

// Usage:
const changes = deepDiff(oldConfig, newConfig);
console.log(changes);
// [{ path: 'database.port', type: 'changed', old: 5432, new: 5433 }, ...]


💡 Pro tip: Add Array.isArray() handling to diff arrays by index, or use a key-based approach for ordered lists.

Previous this week: Bash Disk Audit → Python File Download → SQL Duplicate Finder → JS Deep Diff ⭐