Why Mutation Can Be Dangerous
You'll learn why modifying arrays in place can lead to surprising bugs when multiple parts of your code share the same array.
The Core Problem
When you mutate an array, you're changing the original data structure in memory. If multiple variables point to that same array, they'll all see the changes — even if you didn't intend that! This creates spooky action at a distance: changing data in one place unexpectedly affects code somewhere else entirely.
Think of it like writing in a shared notebook. If you and your friend both use the same notebook, your edits affect what they see. But if you thought you had your own copy, you'd be very surprised when your friend's notes suddenly appeared on "your" pages!
A Simple Example
const shoppingList = ['apples', 'bread', 'milk'];
const backupList = shoppingList; // Both point to the SAME array!
shoppingList.push('eggs');
console.log(backupList); // ['apples', 'bread', 'milk', 'eggs']
// Surprise! The "backup" changed too
You thought backupList was a separate copy, but it's actually pointing to the exact same array in memory. When you mutated shoppingList, backupList reflected those changes because they're the same thing.
Why This Gets Dangerous
In larger programs, arrays get passed to functions, stored in objects, and shared across modules. If you mutate an array somewhere deep in your code, you might break something that relies on the original data. These bugs are hard to find because the mutation happens far away from where the error appears.
Key Takeaway: Mutating arrays is dangerous when multiple references point to the same array. Always consider whether you're modifying shared data, and when in doubt, create a copy before mutating.