JavaScript(JS) array method - copywithin

https://w‮w‬w.theitroad.com

The copyWithin() method is an array method in JavaScript that allows you to copy a sequence of elements within the same array. This method does not modify the length of the array, but instead replaces a sequence of elements with a copy of another sequence of elements within the same array.

Here's the syntax of the copyWithin() method:

array.copyWithin(target, start, end);
  • array is the array that the copyWithin() method is called on.
  • target is the index where the copied sequence of elements should be placed.
  • start is the index where the sequence of elements to be copied starts. The default value is 0.
  • end is the index where the sequence of elements to be copied ends. The default value is array.length.

Here's an example of how to use the copyWithin() method:

let array = [1, 2, 3, 4, 5];

array.copyWithin(1, 3, 5);
console.log(array); // [1, 4, 5, 4, 5]

In this example, we have an array array containing the elements [1, 2, 3, 4, 5]. We use the copyWithin() method to copy the elements from index 3 to index 4 ([4, 5]) and place them starting at index 1 in the array. The console.log() statement outputs the modified array, which now contains the elements [1, 4, 5, 4, 5].

Note that the copyWithin() method does not change the length of the array, and it can be used to overwrite existing elements in the array. Also, the copyWithin() method works with negative indices, which can be used to specify positions relative to the end of the array.