Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

Array.prototype.copyWithin()

Reference for JavaScript Array.prototype.copyWithin(): copy a range of elements to another position in the same array, in place, with negative indexes and overlaps.

The copyWithin() method copies a range of elements from one position of an array to another position in the same array, overwriting what was there. It changes the array in place and returns the same array, but it never changes the array's length.

It is a low-level tool, used for shifting data inside buffers and typed arrays more than in everyday application code.

JavaScript
[1, 2, 3, 4, 5].copyWithin(0, 3); // [4, 5, 3, 4, 5]

Try it

JS Copying a range

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Shifting data inside an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
array.copyWithin(target, start)
array.copyWithin(target, start, end)
Name Description
target Zero-based index where the copied elements are placed. Negative values count from the end.
start Index where copying starts. Negative values count from the end.
end Optional. Index where copying stops, not included. Defaults to the array length. Negative values count from the end.

Return value: the modified array (the same object, not a copy).

Exceptions: a TypeError if the array is frozen, because the method writes to it.

Usage notes

  • Mutates in place and returns the receiver, so result === original.
  • Length never changes. Elements that would land beyond the end are dropped; the source range is cut short instead of growing the array.
  • Overlap is safe. The copy behaves as if the range were copied to a temporary location first, so copyWithin(2, 0) works correctly.
  • Source stays too. It copies; it does not move or erase the source elements. They are only overwritten if the target range covers them.
  • Indexes are clamped to the array bounds, and fractions are truncated.
  • Holes: a hole in the source deletes the element in the target, instead of creating undefined.
  • Typed arrays have the same method with the same behavior, and it works on raw binary data efficiently.
  • Alternatives: for removing the first element of a list, shift() is simpler. To create a changed copy, use slice() and splice() or spread.

Browser support

Array.prototype.copyWithin() is supported in every current browser and JavaScript runtime.