copywithin()

The copyWithin method in JavaScript arrays allows for the duplication of a specified portion of the array using its own elements and subsequently returns the altered array. It is important to note that this method does not alter the length of the resulting array.

Syntax

The syntax for the copyWithin method is expressed as follows:

Example

array.copyWithin(target, start, end)

Parameter

target - The location where the duplicated element is positioned.

start - This parameter is not mandatory. It indicates the index from which the method begins to copy elements. By default, this value is set to 0.

end - This parameter is not mandatory. It specifies the index at which the copying of elements ceases. By default, it is set to array.length - 1.

Return

The modified array.

JavaScript Array copyWithin method example

Let's see some examples of copyWithin method.

Example 1

In this section, we will provide the target value along with the starting and ending indices through the method.

Example

<script>

var arr=["AngularJS","Node.js","JQuery","Bootstrap"]

// place at 0th position, the element between 1st and 2nd position.

var result=arr.copyWithin(0,1,2);

document.writeln(result);

</script>

Output:

Output

Node.js,Node.js,JQuery,Bootstrap

Example 2

Now, let us examine another instance in which we will duplicate two elements.

Example

</script>

var arr=["AngularJS","Node.js","JQuery","Bootstrap"]

// place from 0th position, the elements between 1st and 3rd position.

var result=arr.copyWithin(0,1,3);

document.writeln(result);

</script>

Output:

Output

Node.js,JQuery,JQuery,Bootstrap

Example 3

In this illustration, we will specify solely the target index along with the starting index.

Example

<script>

var arr=["AngularJS","Node.js","JQuery","Bootstrap"];

// place from 1st position, the elements after 2nd position.

var result=arr.copyWithin(1,2);

document.writeln(result);

</script>

Output:

Output

AngularJS,JQuery,Bootstrap,Bootstrap

Example 4

In this illustration, we will specify solely the target index.

Example

<script>

var arr=["AngularJS","Node.js","JQuery","Bootstrap"];

// place from 2nd position, the elements after 0th position.

var result=arr.copyWithin(2);

document.writeln(result);

</script>

Output:

Output

AngularJS,Node.js,AngularJS,Node.js

Input Required

This code uses input(). Please provide values below: