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.
  • Original is modified
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(0, 2));
// [ 2, 3, 4, 5, 4, 5 ]

console.log([0, 1, 2, 3, 4, 5].copyWithin(0, 3));
// [ 3, 4, 5, 3, 4, 5 ]
arrayX.copyWithin(at, start , end)
to index end but not include it.
console.log([0, 1, "x2", "x3", 4].copyWithin(0, 2, 4));
// [ "x2", "x3", "x2", "x3", 4 ]

console.log([0, 1, "x2", "x3", 4].copyWithin(1, 2, 4));
// [ 0, "x2", "x3", "x3", 4 ]

console.log([0, 1, "x2", "x3", 4].copyWithin(2, 2, 4));
// [ 0, 1, "x2", "x3", 4 ]

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

More examples

console.log([0, 1, 2, 3].copyWithin(0, 0)); // [ 0, 1, 2, 3]
console.log([0, 1, 2, 3].copyWithin(1, 0)); // [ 0, 0, 1, 2]
console.log([0, 1, 2, 3].copyWithin(2, 0)); // [ 0, 1, 0, 1]
console.log([0, 1, 2, 3].copyWithin(3, 0)); // [ 0, 1, 2, 0]
console.log([0, 1, 2, 3].copyWithin(4, 0)); // [ 0, 1, 2, 3]
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 ]

JavaScript: Array, add/remove items

BUY ΣJS JavaScript in Depth