JavaScript: Array.prototype.copyWithin

By Xah Lee. Date: . Last updated: .

New in JS2015.

arrayX.copyWithin(at, start )
Take a subarray that began at index start to end, copy them to starting at the index at, override the original values. Return the changed array.
arrayX.copyWithin(at, start , end )
to index end but not include it.
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 in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS Obj Ref

Array

prototype