Skip to main content
Version: 3.14.1

Array.prototype.copyWithin

The copyWithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length.

Syntax

copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)

Parameters

  • target
    • : Zero-based index at which to copy the sequence to, converted to an integer.
      • Negative index counts back from the end of the array — if target < 0, target + array.length is used.
      • If target < -array.length, 0 is used.
      • If target >= array.length, nothing is copied.
      • If target is positioned after start after normalization, copying only happens until the end of array.length (in other words, copyWithin() never extends the array).
  • start optional
    • : Zero-based index at which to start copying elements from, converted to an integer.
      • Negative index counts back from the end of the array — if start < 0, start + array.length is used.
      • If start < -array.length or start is omitted, 0 is used.
      • If start >= array.length, nothing is copied.
  • end optional
    • : Zero-based index at which to end copying elements from, converted to an integer. copyWithin() copies up to but not including end.
      • Negative index counts back from the end of the array — if end < 0, end + array.length is used.
      • If end < -array.length, 0 is used.
      • If end >= array.length or end is omitted, array.length is used, causing all elements until the end to be copied.
      • If end is positioned before or at start after normalization, nothing is copied.

Return value

The modified array.

Description

The copyWithin() method works like C and C++'s memmove, and is a high-performance method to shift the data of an Array. The sequence is copied and pasted as one operation; the pasted sequence will have the copied values even when the copy and paste region overlap.

The copyWithin() method is a mutating method. It does not alter the length of this, but it will change the content of this and create new properties or delete existing properties, if necessary.

The copyWithin() method preserves empty slots. If the region to be copied from is sparse, the empty slots' corresponding new indices are deleted and also become empty slots.

The copyWithin() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.