JS Built-ins
← Array44 / 226
ArrayArray.prototype.copyWithinintermediate

Array.prototype.copyWithin() β€” negative target index

πŸ“– Usage Example
const arr = [1, 2, 3, 4, 5]
arr.copyWithin(-2, 0, 2)  // β†’ [1, 2, 3, 1, 2]
// uses negative target index

Use negative indices with copyWithin() to reference positions from the end of the array.

Array.prototype.copyWithin() β€” negative indices

Like other array methods, copyWithin supports negative indices. copyWithin(-1, 0, 1) copies the first element to the last position.

Challenge: Implement copyToEnd(arr) that copies the first element to the last position using arr.copyWithin(-1, 0, 1).

copyToEnd([1, 2, 3, 4]) // β†’ [1, 2, 3, 1]
copyToEnd([9, 0, 0])    // β†’ [9, 0, 9]
πŸ’‘ Hints (2)
  • β€’ A negative target `-1` refers to the last position in the array.
  • β€’ `copyWithin(-1, 0, 1)` copies just one element (arr[0]) to the last slot.