JavaScript Array copyWithin() method
The copyWithin()
method in JavaScript is used to copy a sequence of elements within the same array to a specified position, overwriting existing elements. This method modifies the original array and can be useful for rearranging or duplicating parts of an array without needing to create a new one.
Syntax:
target
: The index at which to copy the elements to. This can be a positive or negative index.start
(optional): The index at which to start copying elements from. If omitted, it defaults to0
. This can also be a negative index, which will be counted from the end of the array.end
(optional): The index at which to stop copying elements (not inclusive). If omitted, it defaults to the length of the array. This can also be a negative index.
Return Value:
- The modified array after copying the elements.
Key Points:
- The
copyWithin()
method modifies the original array in place and returns it. - If the
target
index is greater than the array length, it will effectively do nothing. - If
start
is greater than or equal toend
, no elements will be copied. - Negative indices count back from the end of the array.
Example 1: Basic usage
Example 2: Using start and end
Example 3: Negative indices
Example 4: Overlapping ranges
Example 5: No elements copied
Summary:
- The
copyWithin()
method provides a simple way to copy elements within an array to different positions, modifying the original array directly. - It is useful for rearranging elements without creating additional copies, making it a powerful tool for in-place array manipulation.
- This method can handle positive and negative indices, allowing flexible manipulation of array contents.