🟑 MediumWhat's Wrong?πŸ› Debug Challenge

Spread only shallow-copies nested arrays

Buggy Code β€” Can you spot the issue?

function sortMatrixRows(matrix) {
  const copy = [...matrix]; // copy of the outer array
  copy.forEach(row => row.sort((a, b) => a - b));
  return copy;
}

const grid = [[3,1,2],[6,4,5],[9,7,8]];
const sorted = sortMatrixRows(grid);

console.log(sorted[0]); // [1, 2, 3] βœ“
console.log(grid[0]);   // [1, 2, 3] β€” MUTATED! Expected [3, 1, 2]

Fixed Code

function sortMatrixRows(matrix) {
  // Deep copy: spread outer array AND each inner row
  return matrix.map(row => [...row].sort((a, b) => a - b));
}

// Alternative: use structuredClone for any depth
function sortMatrixRowsDeep(matrix) {
  const copy = structuredClone(matrix);
  copy.forEach(row => row.sort((a, b) => a - b));
  return copy;
}

const grid = [[3,1,2],[6,4,5],[9,7,8]];
const sorted = sortMatrixRows(grid);

console.log(sorted[0]); // [1, 2, 3] βœ“
console.log(grid[0]);   // [3, 1, 2] βœ“ unchanged

Bug Explained

Bug: [...matrix] creates a new outer array but the inner row arrays are the SAME references. Sorting a row sorts the original row in grid.

Explanation: Spread is shallow β€” inner arrays are not copied, just their references. Sort mutates in place, affecting the original. Copy each row individually with [...row] or use structuredClone().

Key Insight: Spread creates a shallow copy of the TOP-LEVEL container. Nested arrays/objects are still shared references. Deep copy nested structures before mutating them.

More What's Wrong? Debug Challenges

🟒 EasyAccidental global variableβ†’πŸŸ‘ MediumWrong comparison with NaNβ†’πŸ”΄ HardInfinite re-render in React useEffectβ†’πŸŸ‘ MediumArray sort mutates originalβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab