JavaScript Array copyWithin() method


The copyWithin() method in JavaScript is used to copy a sequence of elements within the same array to a specified position, overwriting existing elements. This method modifies the original array and can be useful for rearranging or duplicating parts of an array without needing to create a new one.

Syntax:

array.copyWithin(target, start, end);
  • target: The index at which to copy the elements to. This can be a positive or negative index.

  • start (optional): The index at which to start copying elements from. If omitted, it defaults to 0. This can also be a negative index, which will be counted from the end of the array.

  • end (optional): The index at which to stop copying elements (not inclusive). If omitted, it defaults to the length of the array. This can also be a negative index.

Return Value:

  • The modified array after copying the elements.

Key Points:

  • The copyWithin() method modifies the original array in place and returns it.
  • If the target index is greater than the array length, it will effectively do nothing.
  • If start is greater than or equal to end, no elements will be copied.
  • Negative indices count back from the end of the array.

Example 1: Basic usage

let array = [1, 2, 3, 4, 5]; array.copyWithin(0, 3); // Copy elements from index 3 to index 0 console.log(array); // [4, 5, 3, 4, 5]

Example 2: Using start and end

let array = [1, 2, 3, 4, 5]; array.copyWithin(0, 3, 5); // Copy elements from index 3 to 5 (not inclusive) console.log(array); // [4, 5, 3, 4, 5]

Example 3: Negative indices

let array = [1, 2, 3, 4, 5]; array.copyWithin(-2, -4, -1); // Copy from index -4 to -1 (not inclusive) console.log(array); // [1, 2, 3, 4, 4]

Example 4: Overlapping ranges

let array = [1, 2, 3, 4, 5]; array.copyWithin(2, 0, 3); // Copy elements from index 0 to 3 into index 2 console.log(array); // [1, 2, 1, 2, 3]

Example 5: No elements copied

let array = [1, 2, 3, 4, 5]; array.copyWithin(0, 2, 1); // start > end, so nothing is copied console.log(array); // [1, 2, 3, 4, 5]

Summary:

  • The copyWithin() method provides a simple way to copy elements within an array to different positions, modifying the original array directly.
  • It is useful for rearranging elements without creating additional copies, making it a powerful tool for in-place array manipulation.
  • This method can handle positive and negative indices, allowing flexible manipulation of array contents.