Understanding Mutating vs Non-Mutating Methods
What You'll Learn
You'll learn how to distinguish between array methods that change the original array and those that leave it intact while returning a new value.
The Core Difference
Mutating methods modify the original array directly. When you call them, the array you started with is permanently changed. Think of it like editing a document in place—you're changing the actual file.
Non-mutating methods leave the original array untouched and return a new array or value instead. It's like making a photocopy of a document to work with—the original stays pristine.
Methods You've Already Learned
Mutating methods (they change the original):
push(),pop(),unshift(),shift()splice()reverse()sort()fill()copyWithin()
These methods alter your array in place. After calling them, the array is different.
Non-mutating methods (they return new values):
- Array access with bracket notation (reading only)
- The
lengthproperty (when reading it)
Why This Matters
Understanding this distinction helps you avoid bugs. If you pass an array to a function that calls sort(), the original array outside that function is also sorted! Sometimes that's what you want, but often it's not.
const numbers = [3, 1, 2];
numbers.sort(); // mutates
console.log(numbers); // [1, 2, 3] - original changed!
Knowing whether a method mutates helps you predict your code's behavior and choose the right tool for each situation.
Key Takeaway: Mutating methods change the original array directly, while non-mutating methods preserve it and return new values—always know which type you're using to avoid unexpected side effects.