What is the copyWithin function in JavaScript?

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.

Syntax

copyWithin(insert, copy_from, copy_till)
copyWithin(insert, copy_till)
copyWithin(insert)

Parameters

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 and copy_from arguments arguments optional. If copy_till is not specified, it is assumed to be equal to the array’s length by default. If copy_from is not specified, copying begins from index 0.

Return value

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.

Example

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 array
const sample_array = [ "A", "B", "C", "D", "E", "F","G","H" ];
//print previous array
console.log("Original array: ",sample_array);
//call copyWithin with 3 arguments
sample_array.copyWithin(2, 1, 4);
//print the updated array
console.log("Updated array (3 arguments): ",sample_array);
//call copyWithin with 2 arguments
sample_array.copyWithin(2, 1);
//print the updated array
console.log("Updated array (2 arguments): ",sample_array);
//call copyWithin with 1 argument
sample_array.copyWithin(2);
//print the updated array
console.log("Updated array (2 arguments): ",sample_array);

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved