JavaScript Array copyWithin() method

he copyWithin() method in JavaScript is used to copy a sequence of elements within an array to another position in the same array. This method modifies the array in place, meaning that it changes the existing array instead of creating a new one.

Here is an example of how the copyWithin() method works:

const array1 = [1, 2, 3, 4, 5];

// copy the first two elements to the end of the array
const result = array1.copyWithin(array1.length, 0, 2);

// the result will be: [1, 2, 3, 4, 1, 2]

In the code example above, we first declare an array called array1 that contains the numbers 1 through 5. We then use the copyWithin() method to copy the first two elements (1 and 2) to the end of the array. The copyWithin() method takes three arguments: the target index (where the copied sequence will be inserted), the start index (the first element of the sequence to be copied), and the end index (the last element of the sequence to be copied). In this case, we use array1.length as the target index (which is equivalent to appending the copied sequence to the end of the array), 0 as the start index (which is the first element of the array), and 2 as the end index (which is the third element of the array).

As a result of calling the copyWithin() method, the array1 array is modified in place and now contains the following elements: 1, 2, 3, 4, 1, 2.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: