copyWithin(): Copying Elements Within the Same Array
You'll learn how to copy a section of an array to another position within the same array, overwriting existing elements.
What It Does
The copyWithin() method copies a sequence of elements from one part of an array and pastes them into another part of the same array. It mutates the array in place, similar to splice() or fill(), but instead of adding new values or removing elements, it duplicates existing ones internally.
Think of it like copy-pasting text within the same document—you're not creating a new document, just reorganizing what's already there.
How It Works
The syntax is: array.copyWithin(target, start, end)
- target: The index where you want to paste the copied elements
- start: The index where you start copying from (inclusive)
- end: The index where you stop copying (exclusive, optional—defaults to array length)
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
// arr is now [4, 5, 3, 4, 5]
// Copied elements from index 3 onward, pasted at index 0
const arr2 = ['a', 'b', 'c', 'd', 'e'];
arr2.copyWithin(2, 0, 2);
// arr2 is now ['a', 'b', 'a', 'b', 'e']
// Copied 'a' and 'b' (indices 0-2), pasted at index 2
Like splice(), negative indices count from the end:
const arr3 = [1, 2, 3, 4, 5];
arr3.copyWithin(0, -2);
// arr3 is now [4, 5, 3, 4, 5]
The method returns the modified array (useful for chaining), but the original array is changed.
Key Takeaway: Use copyWithin() to duplicate a slice of an array to another position within the same array—it mutates in place and is useful for low-level array manipulations like buffer management.