JavaScript Array copyWithin() Method

The copyWithin() works like a C and C++ memmove and is the high-performance method to shift a data of an Array. It especially applies to a TypedArray method of the same name. The sequence is copied and pasted as only one operation; the pasted sequence will have copied values even when a copy-and-paste region overlap.

Javascript Array copyWithin

JavaScript Array copyWithin() is a built-in method that copies part of an array to the same array. It returns it without modifying its size, i.e., copies the array element of an array within the same array.

The copyWithin() method copies array elements to another position in the array, overwriting the existing values. The copyWithin() method will never add more items to the array. Instead, the array copyWithin method overwrites the original array.

The copyWithin() function is intentionally generic and does not require this value to be the Array object.

The copyWithin() method is the mutable method. It does not modify this length but will change its content and create new properties if necessary.

Syntax

See the following syntax of the copyWithin() method.

array.copyWithin(target, start, end)

Parameters

The target parameter is required, and it is the index position to copy the elements too.

The start parameter is optional, and the index position is to start copying elements.

The end parameter is optional, and the index position is to stop copying elements from (default is array.length).

Example

See the following code example.

// app.js

let shows = ["Pink Panther", "Chhota Bheem", "Oggy", "Tom and Jerry", "Doraemon"];
console.log(shows.copyWithin(2, 0, 2));

See the following output.

Javascript Array copyWithin Example

Now, see more examples.

console.log([21, 19, 46, 4, 5].copyWithin(-2));

console.log([21, 19, 46, 4, 5].copyWithin(0, 3));

console.log([21, 19, 46, 4, 5].copyWithin(0, 3, 4));

See the following output.

JS Array copyWithin Tutorial

So, the array copyWithin() method copies the part of the given array with its elements and returns the modified array. The copyWithin() method doesn’t change the length of the modified array.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.