The copyWithin() method in JavaScript is used to shallow copy a portion of an array to another location in the same array, overwriting the existing elements. This method does not change the length of the array.
Syntax
array.copyWithin(target, start, end);
Parameters
Parameter | Description |
---|---|
target | The index at which to start copying elements to. |
start | The index at which to start copying elements from. |
end | The index at which to stop copying elements (optional). |
Return Value
Return Type | Description |
---|---|
Array | The modified array with the copied elements. |
Example 1: Copying Elements Within the Same Array
This code demonstrates how to use the copyWithin() method to copy elements within the same array arr, starting from index 0 and copying elements from index 3 to index 5.
let arr = [1, 2, 3, 4, 5]; arr.copyWithin(0, 3, 5); console.log("Copied Array: " + arr);
Output:
Copied Array: 4, 5, 3, 4, 5
Example 2: Copying Elements with Negative Indices
This code demonstrates how to use the copyWithin() method with negative indices. It copies elements from index -2 to index -4 and places them starting at index 0.
let arr = [1, 2, 3, 4, 5]; arr.copyWithin(0, -4, -2); console.log("Copied Array: " + arr);
Output:
Copied Array: 2, 3, 3, 4, 5
Example 3: Copying Elements with Omitted end
Parameter
This code demonstrates how to use the copyWithin() method with an omitted end parameter. It copies elements starting from index 0 to the end of the array and places them starting at index 3.
let arr = [1, 2, 3, 4, 5]; arr.copyWithin(3, 0); console.log("Copied Array: " + arr);
Output:
Copied Array: 1, 2, 3, 1, 2
Example 4: Copying Elements with Omitted start
and end
Parameters
This code demonstrates how to use the copyWithin() method with omitted start and end parameters. It copies all elements starting from index 0 to the end of the array and places them starting at index 2.
let arr = [1, 2, 3, 4, 5]; arr.copyWithin(2); console.log("Copied Array: " + arr);
Output:
Copied Array: 1, 2, 1, 2, 3
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
45 | 12 | 32 | 32 | 9 |