Array.prototype.copyWithin()
copyWithin(target, start, end) Returns:
Array · Updated March 13, 2026 · Array Methods array copyWithin mutating
copyWithin() copies a sequence of array elements to another position in the array, overwriting existing values. It mutates the array in place and returns the modified array. This method is useful for moving elements around without creating a new array.
Syntax
arr.copyWithin(target, start, end)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
target | integer | — | Zero-based index where copied elements will be written. Negative indices count from the end. |
start | integer | 0 | Zero-based index to start copying elements from. Negative indices count from the end. |
end | integer | arr.length | Zero-based index to stop copying (exclusive). Negative indices count from the end. |
Examples
Basic usage
const fruits = ["apple", "banana", "cherry", "date", "elderberry"];
fruits.copyWithin(0, 2, 5);
console.log(fruits);
// ["cherry", "date", "elderberry", "date", "elderberry"]
Using negative indices
const nums = [1, 2, 3, 4, 5];
nums.copyWithin(0, -2);
console.log(nums);
// [4, 5, 3, 4, 5]
Overlapping copy
const letters = ["a", "b", "c", "d", "e"];
letters.copyWithin(2, 0, 2);
console.log(letters);
// ["a", "b", "a", "b", "e"]
Moving elements to new position
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(3, 0, 2);
console.log(arr);
// [1, 2, 3, 1, 2]
Target beyond array length
const items = ['a', 'b', 'c'];
items.copyWithin(4, 0, 2);
console.log(items);
// ['a', 'b', 'c', empty, 'a', 'b']
Shifting elements left
const data = [1, 2, 3, 4, 5];
// Copy from index 2 to end, paste at index 0
data.copyWithin(0, 2);
console.log(data);
// [3, 4, 5, 4, 5]
Duplicate array portion
const pattern = [1, 2, 3, 1, 2, 3, 1, 2, 3];
pattern.copyWithin(3, 0, 3);
console.log(pattern);
// [1, 2, 3, 1, 2, 3, 1, 2, 3]
Common Patterns
In-place rotation
function rotate(arr, by) {
const len = arr.length;
if (by >= len) by = by % len;
arr.copyWithin(len, len - by, len);
arr.copyWithin(len - by, 0, len - by);
arr.copyWithin(0, len, len + by);
return arr;
}
console.log(rotate([1, 2, 3, 4, 5], 2)); // [4, 5, 1, 2, 3]
Fill with repeating pattern
const arr = [1, 2, 3, 4, 5, 6];
arr.copyWithin(3, 0, 3);
console.log(arr);
// [1, 2, 3, 1, 2, 3]
Behavior Notes
- The method modifies the original array
- If target >= start, original values at those positions are used for copying
- Works with sparse arrays but treats holes as undefined values
See Also
- array::splice — Add/remove elements
- array::fill — Fill array with value