The copyWithin() method allows you to copy a sequence of elements within an array to another position within the same array. It modifies the original array in place and returns a reference to the modified array.
The syntax for copyWithin() is as follows:
array.copyWithin(target, start, end)
target: The index at which to copy the elements to. It can be a positive or negative number. If it is negative, it will be counted from the end of the array. If the target index is greater than or equal to the length of the array, no elements will be copied.
start: The index at which to start copying elements from. It is optional and defaults to 0 if not provided. If it is negative, it will be counted from the end of the array.
end: The index at which to stop copying elements from. It is optional and defaults to the length of the array if not provided. If it is negative, it will be counted from the end of the array.
Example:
const array = [1, 2, 3, 4, 5];
// Copy elements starting from index 3 to index 0
array.copyWithin(0, 3);
console.log(array); // Output: [4, 5, 3, 4, 5]
// Copy elements starting from index 1 to index 3
array.copyWithin(3, 1, 2);
console.log(array); // Output: [4, 5, 3, 5, 5]
Browser compatibility
If you like my work and want to support me to work hard, please donate via:
Revolut website payment or use the QR code above.
Thanks a bunch for supporting me! It means a LOT 😍
Top comments (0)