The Return Values of Mutating Methods
You'll learn: Each mutating array method returns something different—some give you the modified array, others return what was removed, and some return the new length.
What Gets Returned?
When you use a mutating method to change an array, JavaScript doesn't just silently modify it—each method also hands you back a return value. Understanding what you get back is crucial for writing clean, bug-free code.
Think of mutating methods like different types of kitchen tools: a knife cuts your vegetables and leaves the sliced pieces on the board (returns what was removed), while a blender transforms your ingredients and shows you the final smoothie (returns the modified result).
The Three Return Patterns
Methods that return the new length:
push()andunshift()return the array's new length after adding elementsarr.push(5)returns how many elements are now inarr
Methods that return removed elements:
pop()andshift()return the single element that was removedsplice()returns an array of all removed elements (even if just one)
Methods that return the modified array itself:
reverse(),sort(),fill(), andcopyWithin()all return a reference to the same array after modifying it- This allows method chaining:
arr.reverse().fill(0)
Why This Matters
Knowing what gets returned prevents confusion. If you write let removed = arr.push(5), you'll get a number (the length), not the array. If you use let sorted = arr.sort(), both sorted and arr point to the same array—they're not copies.
Key Takeaway: Mutating methods return different things—lengths (push/unshift), removed elements (pop/shift/splice), or the array itself (reverse/sort/fill/copyWithin). Know what you're getting back!