JavaScript Array copyWithin()

Posted by

Method

JavaScript Array copyWithin() Method

The copyWithin() method of the JavaScript Array object is used to copy a sequence of array elements within the array. The elements copied will replace existing elements in the array.

Syntax

The syntax for the copyWithin() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

arr.copyWithin(target, start[, end])

[/dm_code_snippet]

Parameters

  • target: An integer that specifies at what position to copy the elements to. If negative, it will begin that many elements from the end.
  • start: An integer that specifies where to start copying elements from. If negative, it will begin that many elements from the end.
  • end: (optional) An integer that specifies where to end copying elements from. If negative, it will end that many elements from the end.

Return Value

The copyWithin() method returns the modified array.

Example

Let’s look at an example of the copyWithin() method:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var arr = [1, 2, 3, 4, 5];

// Copy the 3rd element to the 0 index
arr.copyWithin(0, 2, 3);

console.log(arr); // [3, 2, 3, 4, 5]

[/dm_code_snippet]

In the example above, we have an array with 5 elements. We use the copyWithin() method to copy the 3rd element to the 0 index. As you can see, the 3rd element (the value 3) is now at the 0 index and the previous element at the 0 index (the value 1) is now at the 3rd index.

Browser Support

The copyWithin() method is supported in the following browsers:

  • Chrome 45+
  • Edge 12+
  • Firefox 36+
  • Safari 10+
  • Opera 32+