In this section, we will learn what the copyWithin() element is and how to use it in JavaScript.
JavaScript Arrays copyWithin() Method
The `copyWithin()` method is used to copy elements within the body of an array from one position to another.
Basically, this method moves around elements of an array inside the body of that array itself.
Array copyWithin() Syntax:
array.copyWithin(target, start, end)
Array copyWithin() Method Parameters:
The method takes 3 arguments:
- The first argument is the target index position, where the copied elements should be put in.
- The second argument is the index position where copying elements should start.
- The third argument is the end index to stop copying elements from (exclusive). The default is the length of the array.
If any of the arguments are negative, that value will be used as an offset from the end of the array. For instance, if the first argument is -2 and the length of the array is 8, that means the actual index number for the first argument will be 6 because 8 – 2 is 6.
Array copyWithin() Method Return Value:
The return value of this method is a reference to the array that we’ve just edited and moved around its elements.
Example: using Array copyWithin() method in JavaScript
const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"]; arr.copyWithin(2,0); console.log(arr);
Output:
["Tesla", "Google", "Tesla", "Google", "Microsoft", "Amazon"]
Here, the target position is set to 2, and this means the copied elements will be put into this index and those indices that come afterwards.
The start position is set to 0 and so it means the copy should start at the position 0 of the array.
The last argument is ignored, so that means the copy operation will move on to the last element of the array (as long as there’s a space in the array for the copied elements).
JavaScript Array copyWithin() Method Example:
const arr = ["Tesla","Google","Microsoft","Amazon","Facebook","Twitter"]; arr.copyWithin(2,1,4); console.log(arr);
Output:
["Tesla", "Google", "Google", "Microsoft", "Amazon", "Twitter"]