The copyWithin() method of the Array class in JavaScript copies a sequence of array elements within an array to a different position in the same array, without modifying its length.
There are 2 variations for the syntax of Array.copyWithin() method. They are:
copyWithin(target, start)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
target | required | The index at which to copy the sequence to. |
start | required | The index at which to start copying elements from. |
This method copies the sequence of array elements from start to the end of the array to the target position. The length of the array is not modified.
Returns value of type Array
.
copyWithin(target, start, end)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
target | required | The index at which to copy the sequence to. |
start | required | The index at which to start copying elements from. |
end | optional | The index at which to end copying elements. This is exclusive. |
This method copies the sequence of array elements from start to end (not included) to the target position. The length of the array is not modified.
Returns value of type Array
.
In JavaScript, we can use the copyWithin() method to copy a sequence of elements within the same array.
For example,
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
console.log(arr);
[4, 5, 3, 4, 5]
We can use the copyWithin() method to copy a sequence of elements within the same array, specifying the end index.
For example,
const arr = ['a', 'b', 'c', 'd', 'e'];
arr.copyWithin(1, 3, 4);
console.log(arr);
['a', 'd', 'c', 'd', 'e']
In JavaScript, we can use the copyWithin() method to copy a sequence of numbers within the same array.
For example,
const numArr = [10, 20, 30, 40, 50];
numArr.copyWithin(2, 0, 2);
console.log(numArr);
[10, 20, 10, 20, 50]
In this JavaScript tutorial, we learned about copyWithin() method of Array: the syntax and few working examples with output and detailed explanation for each example.