rashmi agar
26 posts
Mar 08, 2025
10:02 PM
|
JavaScript provides a variety of methods to manipulate arrays efficiently, and one such method is js copywithin (). This method allows us to copy a portion of an array to another location within the same array without modifying its length. It’s a useful tool when we need to rearrange data without creating a new array.
Syntax of copyWithin() javascript Copy Edit array.copyWithin(target, start, end) target: The index where the copied elements will be placed. start (optional): The index from where copying starts. Default is 0. end (optional): The index where copying stops (not included). Default is the length of the array. Example 1: Basic Usage javascript Copy Edit let arr = [1, 2, 3, 4, 5]; arr.copyWithin(0, 3); console.log(arr); // Output: [4, 5, 3, 4, 5] Here, elements starting from index 3 (4, 5) are copied to the beginning of the array.
Example 2: Using start and end Parameters javascript Copy Edit let arr = [10, 20, 30, 40, 50, 60]; arr.copyWithin(2, 0, 3); console.log(arr); // Output: [10, 20, 10, 20, 30, 60] Here, elements from index 0 to index 2 (10, 20, 30) are copied starting at index 2.
Example 3: Negative Indexing javascript Copy Edit let arr = [5, 10, 15, 20, 25]; arr.copyWithin(-2, 0, 2); console.log(arr); // Output: [5, 10, 15, 5, 10] Negative values allow indexing from the end of the array. In this case, 5 and 10 are copied to the last two positions.
Key Points to Remember copyWithin() modifies the original array (it does not create a new one). It does not alter the length of the array. It can overwrite existing elements but does not insert new ones. It supports negative indices, making it flexible for different use cases. When to Use copyWithin()? Rearranging elements in an array efficiently. Avoiding unnecessary array cloning when repositioning elements. Manipulating data structures without extra memory allocation. Conclusion The copyWithin() method is a powerful yet simple tool in JavaScript that helps modify arrays in place. Understanding its behavior with different parameters and edge cases can help optimize array operations effectively.
|