JavaScript Array copyWithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length. It modifies the original array.
Syntax
array.copyWithin(target, start, end)
Parameters
- target(required): It is the index position to copy the elements.
- start(optional): It is the index position to start copying elements. The default is 0.
- end(optional): It is an index position to stop copying elements from (default is array.length).
Return value
Example 1: How to Use the Array copyWithin() method
let shows = ["Pink Panther", "Chhota Bheem", "Oggy", "Tom and Jerry", "Doraemon"];
console.log(shows.copyWithin(3, 0, 2));
let num = [1,7,14,21];
console.log(num.copyWithin(1, 0));
Output
[
'Pink Panther',
'Chhota Bheem',
'Oggy',
'Pink Panther',
'Chhota Bheem'
]
[ 1, 1, 7, 14 ]
Example 2: Passing negative parameter
let num = [1,7,14,21];
console.log(num.copyWithin(-2));
Output
[ 1, 7, 1, 7 ]
In this example, the target index is -2, start and end index are not provided. So by default, the start is 0 and end is the array length. Then it will place these copied elements starting from index -2.
- The element at index -4 (1) is copied to index -2, overwriting the value 14.
- The element at index -3 (7) is copied to index -1, overwriting the value 21.
Example 3: Using sparse arrays
const ages = [26, 27, 26, , 28, 28, , 29, ];
console.log(ages.copyWithin(2, 1, 2));
Output
[ 26, 27, 27, <1 empty item>, 28, 28, <1 empty item>, 29 ]
Example 4: Passing non-array objects
const arrayLike = {
length: 5,
3: 19,
};
console.log(Array.prototype.copyWithin.call(arrayLike, 0, 3));
console.log(Array.prototype.copyWithin.call(arrayLike, 3, 1));
Output
{ '0': 19, '3': 19, length: 5 }
{ '0': 19, length: 5 }
Browser Compatibility
- Google Chrome 45
- Edge 12
- Firefox 32
- Safari 9
- Opera 32