const original = [3, 1, 2];
const sorted = original;
sorted.sort();
console.log(original.join(','));
console.log(sorted.join(','));const original = [3, 1, 2];
const sorted = [...original];
sorted.sort();
console.log(original.join(','));
console.log(sorted.join(','));Bug: = for arrays copies the reference, not the data. sorted and original point to the same array. Sorting one sorts both.
Explanation: Spread [...original] creates a new independent array. Sorting sorted no longer affects original.
Key Insight: = for arrays copies the reference. Use [...arr] or Array.from(arr) to create an independent copy.