What does copyWithin() do?
The copyWithin() method is one of the most "underrated" yet powerful tools for working with arrays in JavaScript.
It lets you copy part of an array's elements to another place within the same array, without changing its length.
Syntax:
javascript
arr.copyWithin(target, start, end);| Parameter | Description |
|---|---|
target | The index to which elements are copied |
start | The index from which copying starts (inclusive) |
end | The index where it ends (not including this index). Optional. If omitted, it copies to the end of the array |
Example 1 - basic
javascript
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
console.log(arr); // [4, 5, 3, 4, 5]Breakdown:
target = 0→ insert starting at position 0start = 3→ start copying from index 3- copy
[4, 5] - result:
[4, 5, 3, 4, 5]
Example 2 - with start and end
javascript
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(1, 3, 5);
console.log(arr); // [1, 4, 5, 4, 5]- Copy elements
[4, 5](from 3 to 5, not including 5) - Insert starting at position
1
Example 3 - negative indexes
javascript
const arr = [10, 20, 30, 40, 50];
arr.copyWithin(-2, 0, 2);
console.log(arr); // [10, 20, 30, 10, 20]-2→ means "insert starting from the second element from the end"- copy
[10, 20]and insert it at the end.
Behavior details
| Property | Description |
|---|---|
| Mutates the array | Yes |
| Returns | The modified array |
| Array length | Does not change |
| Copies within the array | Yes |
| Return value | A reference to the same array (this) |
Practical usage example:
Can be used to "shift" values within an array without creating a new one:
javascript
const buffer = [1, 2, 3, 4, 5];
buffer.copyWithin(1, 0, 3);
console.log(buffer); // [1, 1, 2, 3, 5]In short:
| What it does | Copies part of an array to another place within it |
|---|---|
| Changes the original array | Yes |
| Returns | The array itself |
| Does not change the length | Yes |
| Example | [1,2,3,4,5].copyWithin(0,3) → [4,5,3,4,5] |
Summary:
copyWithin()is a way to move or duplicate elements within an array without creating a new array and without changing its length.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.