Lesson 2
Array mutation
Build a practical mental model for array mutation and use it in working JavaScript.
By the end, you will be able to…
- Explain array mutation in your own words
- Use array mutation in a small program
- Recognize and debug a common failure mode
Build the mental model
push, pop, splice, sort, and reverse all mutate the original array in place, while spreading into a new array first lets you change a copy without affecting the original.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
Accidentally mutating an array that another part of the program still holds a reference to is one of the most common sources of 'spooky action at a distance' bugs.
Real-world example
React and other UI frameworks require you to create new arrays instead of mutating state directly, precisely to avoid this class of bug.
Common mistakes
- Sorting an array in place when the original order was needed elsewhere
- Assuming array methods always return a new array (many mutate and return the array itself, or a removed item)
- Forgetting splice mutates while slice does not
Try it yourself
Challenge
Fix sortedCopy so it returns a newly sorted array without mutating the input.
Knowledge check
Which of these array methods mutates the original array?
Summary
Know which array methods mutate (push, pop, splice, sort, reverse) and copy first with spread when you need to preserve the original.