• JavaScript Video Tutorials

JavaScript - Array copyWithin() Method



In Javascript, the Array.copyWithin() method is used to copy array elements from one position to another in the specified array. This method returns the modified array after copying the elements.

The copyWithin() method overwrites the existing elements in the array without changing its length. This method does not add any "new" items to the array.

If any of the arguments are negative, the index will be counted backward. For instance, -1 represents the last element, and so on.

Syntax

Following is the syntax of Javascript Array.copyWithin() method −

copyWithin(target, start, end)

Parameters

This method accepts three parameters. The same is described below −

  • target − The index where the copied elements should be pasted.
  • start − The index where the copying should start (default value is 0).
  • end (optional) − The index where the copying should end (default value is array length).

Return value

This method returns the modified array with the copied elements.

Examples

Example 1

In the following example, we are copying the elements starting from index 0 and placing them starting from index 3 using the Javascript Array.copyWithin() method −

<html>
<body>
   <script>
      const array = ['apple', 'banana', 'cherry', 'date', 'grapes'];
      array.copyWithin(3, 0);
      document.write(array);
   </script>
</body>
</html>

Output

apple,banana,cherry,apple,banana

Example 2

In the example below, we are copying the last two elements and placing them at index -3 (counting from the end) −

<html>
<body>
   <script>
      const array = ['apple', 'banana', 'cherry', 'date', 'grapes'];
      array.copyWithin(-3, -2);
      document.write(array);
   </script>
</body>
</html>

Output

apple,banana,date,grapes,grapes

Example 3

Here, we are copying the elements starting from index 1 to index 3 and placing them starting from index 0 −

<html>
<body>
   <script>
      const array = ['apple', 'banana', 'cherry', 'date', 'grapes'];
      array.copyWithin(0, 1, 4);
      document.write(array);
   </script>
</body>
</html>

Output

banana,cherry,date,date,grapes
Advertisements