copyWithin() Function is used to copy array elements and place it in some other location.
Let us say, we have a Array that contains five names, Mohan, Kriti, Philip, Salim and Andrew. And we want to take the name Mohan and Kriti and replace them with Philip and Salim.
In other words, Philip and Salim would be replaced by Mohan and Kriti.
<html> <body> <script> var x = ["Mohan", "Kriti", "Philip", "Salim", "Andrew"] x.copyWithin(2, 0, 2) document.write(x) </script> </body> </html>
So, we have an Array that has 5 names.
So, all we have done is, used the copyWithin() method to copy the elements at index 0 till index 1(The end index represents length i.e. 1+1) and copy them to index 2.
x.copyWithin(2, 0, 2)
And we get the below Array.
Let us see the next example, where we want to copy Kriti and replace with Salim.
So, Kriti is at index 1(Should be the start index) and it has to be placed at index 3(Where Salim resides). And only Kriti has to be copied, so we can give the end index as 1+1 i.e. 2.
x.copyWithin(3, 1, 2)
Let us write the code for it.
<html> <body> <script> var x = ["Mohan", "Kriti", "Philip", "Salim", "Andrew"] x.copyWithin(3, 1, 2) document.write(x) </script> </body> </html>
And as we can see, Salim is replaced with Kriti.