The copyWithin
function in JavaScript is used to copy a series of array elements, stored sequentially in an array object, a different index in the same array.
Old data elements present in the range of indexes specified by the user are replaced.
copyWithin(insert, copy_from, copy_till)
copyWithin(insert, copy_till)
copyWithin(insert)
The copyWithin
function takes up to 3 arguments:
insert
- index from which sequential insertion of array elements will start.copy_from
- index of the first array element to be copied.copy_till
- index of the array element stored after the element that was last copied. Array element at this index is not included.The
copy_till
andcopy_from
arguments arguments optional. Ifcopy_till
is not specified, it is assumed to be equal to the array’s length by default. Ifcopy_from
is not specified, copying begins from index0
.
The copyWithin
function returns the edited array.
The length of the edited array is the same as that of the original array. Length is not changed.
The program below declares an array of characters and calls the copyWithin
function thrice.
The first call is made with all three arguments of the copyWithin
function. Array elements stored between index 1
and 4
, excluding the element at index 4
, replace the array elements stored at and after index 2
.
The second call is made with the first 2 arguments only. In this call, array elements stored between index 1
and the end of the array replace data elements stored at and after index 2
.
The third call is made with just 1 argument. The entire array replaces the original array. Data replacement, like before, starts from index 2
.
The original and modified arrays have been printed using the console.log
function to observe any difference.
//declare arrayconst sample_array = [ "A", "B", "C", "D", "E", "F","G","H" ];//print previous arrayconsole.log("Original array: ",sample_array);//call copyWithin with 3 argumentssample_array.copyWithin(2, 1, 4);//print the updated arrayconsole.log("Updated array (3 arguments): ",sample_array);//call copyWithin with 2 argumentssample_array.copyWithin(2, 1);//print the updated arrayconsole.log("Updated array (2 arguments): ",sample_array);//call copyWithin with 1 argumentsample_array.copyWithin(2);//print the updated arrayconsole.log("Updated array (2 arguments): ",sample_array);
Free Resources