Array.copyWithin()
The Array.copyWithin()
method in JavaScript is used to shallowly copy a portion of an array to another location within the same array, without changing its size. This operation modifies the original array and does not create a new one.
Syntax
array.copyWithin(target, start)
array.copyWithin(target, start, end)
Parameters
Parameter | Description |
---|---|
target | The index at which to copy the sequence to. If negative, it is treated as array.length + target . |
start | The index at which to start copying elements from. If negative, it is treated as array.length + start . |
end (Optional) | The index at which to stop copying elements (exclusive). If omitted, it defaults to the array’s length. If negative, it is treated as array.length + end . |
Return Value
The copyWithin()
method returns the modified array after copying the specified elements.
Examples
1. Copying Within the Array
This example demonstrates how to copy elements within an array using copyWithin()
.
const array = [1, 2, 3, 4, 5];
// Copy elements starting from index 0 to index 3
array.copyWithin(3, 0);
console.log(array);
Output
[1, 2, 3, 1, 2]
Here, elements [1, 2, 3]
from the start of the array are copied to the position starting at index 3
.
2. Using end
Parameter
By specifying the end
parameter, you can control the range of elements to copy.
const array = [1, 2, 3, 4, 5];
// Copy elements from index 1 to index 4 (exclusive) to index 0
array.copyWithin(0, 1, 4);
console.log(array);
Output
[2, 3, 4, 4, 5]
Elements [2, 3, 4]
(indices 1
to 3
) are copied to the position starting at index 0
.
3. Using Negative Indices
Negative indices allow you to specify positions relative to the end of the array.
const array = [1, 2, 3, 4, 5];
// Copy elements starting from the second-to-last position to the beginning
array.copyWithin(0, -2);
console.log(array);
Output
[4, 5, 3, 4, 5]
Here, elements [4, 5]
(starting from index -2
) are copied to the beginning of the array.
4. Copying Subarray to Overlapping Range
This example shows how overlapping ranges behave during copying.
const array = [1, 2, 3, 4, 5];
// Copy elements from index 1 to index 3 to index 2
array.copyWithin(2, 1, 3);
console.log(array);
Output
[1, 2, 2, 3, 5]
Elements [2, 3]
(indices 1
to 2
) are copied to the position starting at index 2
, overwriting part of the array.
5. No Changes When start
Equals end
If start
and end
specify an empty range, the array remains unchanged.
const array = [1, 2, 3, 4, 5];
// No elements are copied as start and end define an empty range
array.copyWithin(0, 2, 2);
console.log(array);
Output
[1, 2, 3, 4, 5]
No changes occur because the start
and end
parameters define an empty range.