Array.prototype.copyWithin
Shallow copies part of an array to another location in the same array and returns it without modifying its length
Syntax
array.copyWithin(target, start?, end?)Parameters
| Parameter | Type | Description |
|---|---|---|
| target | number | Zero-based index to copy the sequence to |
| start | number | Zero-based index to start copying from |
| end | number | Zero-based index at which to end copying |
Return Value
The modified array
Examples
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3);
console.log(arr); // [4, 5, 3, 4, 5]const arr = [1, 2, 3, 4, 5];
arr.copyWithin(1, 3, 4);
console.log(arr); // [1, 4, 3, 4, 5]const arr = ['a', 'b', 'c', 'd', 'e'];
arr.copyWithin(0, 2, 4);
console.log(arr); // ['c', 'd', 'c', 'd', 'e']Understanding Array.prototype.copyWithin
The Array.prototype.copyWithin method in JavaScript shallow copies part of an array to another location in the same array and returns it without modifying its length. It belongs to the Array object and is one of the most widely used methods for working with array values in modern JavaScript and TypeScript applications.
The method signature is array.copyWithin(target, start?, end?). It accepts 3 parameters: target, start, end. When called, it returns the modified array. Understanding when and how to use copyWithin() helps you write more expressive, readable code.
Common use cases for Array.prototype.copyWithin include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like array-fill, array-splice, array-slice, enabling you to chain operations together for complex data manipulation pipelines.
Browser support for Array.prototype.copyWithin is excellent across all modern browsers including Chrome, Firefox, Safari, and Edge. It is also fully supported in Node.js and Deno. For older environments, transpilation with Babel or a polyfill may be needed.
Browser Compatibility
Supported in all modern browsers (Chrome, Firefox, Safari, Edge) and Node.js. Part of the ECMAScript standard.
Related Methods
Array.prototype.fillChanges all elements within a range of indices in an array to a static value, returning the modified array
Array.prototype.spliceChanges the contents of an array by removing or replacing existing elements and/or adding new elements in place
Array.prototype.sliceReturns a shallow copy of a portion of an array into a new array object selected from start to end (end not included)
More Array Methods
Other methods in the Array object
Related Tools
More Array Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.