JS: Array.prototype.copyWithin

By Xah Lee. Date: . Last updated: .

New in ES2015.

myArray.copyWithin (at, start )

myArray.copyWithin (at, start , end )

Take a subarray that began at index start to index end (but not include end), copy them to starting at the index of at (override the original values).

Default value of end is myArray.length

Return the changed array.

myArray is modified.

All arguments can be negative. When negative, it's counted from the end.

const ar = ['A', 'B', 'C', 'D', 'E'];

// move the slice ['A', 'B'] (of index 0 to 2 not including 2), to a position starting at index 1
console.log(ar.copyWithin(1,0,2));
// [ 'A', 'A', 'B', 'D', 'E' ]

// original is modified
console.log(ar);
// [ 'A', 'A', 'B', 'D', 'E' ]
const ar = ['A', 'B', 'C', 'D', 'E'];
//         0   1    2    3    4

console.log(ar.copyWithin(0,3,4));
// [ 'D', 'B', 'C', 'D', 'E' ]

More examples

console.log([0,1,2,3,4].copyWithin(0, 0)); // [ 0, 1, 2, 3, 4]

console.log([0,1,2,3,4].copyWithin(1, 0)); // [ 0, 0, 1, 2, 3]

console.log([0,1,2,3,4].copyWithin(2, 0)); // [ 0, 1, 0, 1, 2]

console.log([0,1,2,3,4].copyWithin(3, 0)); // [ 0, 1, 2, 0, 1]

console.log([0,1,2,3,4].copyWithin(4, 0)); // [ 0, 1, 2, 3, 0]
console.log([0,1,2,3,4,5].copyWithin(0, 1)); // [ 1, 2, 3, 4, 5, 5 ]
console.log([0,1,2,3,4,5].copyWithin(1, 1)); // [ 0, 1, 2, 3, 4, 5 ]
console.log([0,1,2,3,4,5].copyWithin(2, 1)); // [ 0, 1, 1, 2, 3, 4 ]
console.log([0,1,2,3,4,5].copyWithin(3, 1)); // [ 0, 1, 2, 1, 2, 3 ]
console.log([0,1,2,3,4,5].copyWithin(4, 1)); // [ 0, 1, 2, 3, 1, 2 ]
console.log([0,1,2,3,4].copyWithin(0, 2 ,3)); // [ 2, 1, 2, 3, 4 ]

console.log([0,1,2,3,4].copyWithin(1, 2 ,3)); // [ 0, 2, 2, 3, 4 ]

console.log([0,1,2,3,4].copyWithin(2, 2 ,3)); // [ 0, 1, 2, 3, 4 ]

console.log([0,1,2,3,4].copyWithin(3, 2 ,3)); // [ 0, 1, 2, 2, 4 ]

console.log([0,1,2,3,4].copyWithin(4, 2 ,3)); // [ 0, 1, 2, 3, 2 ]

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog