Syntax
arr.fill(value, start, end)
arr.copyWithin(target, start, end)Examples
fill() - Initializing an Array
A common pattern for creating an array of a fixed size with default values.
const zeros = new Array(5).fill(0);
console.log(zeros); // [0, 0, 0, 0, 0]
const partial = [1, 2, 3, 4, 5];
partial.fill(0, 1, 3); // fill with 0, starting at index 1, up to (not including) index 3
console.log(partial); // [1, 0, 0, 4, 5]copyWithin() - Copying Within the Same Array
Shifting a section of elements to overwrite another section.
const arr = [1, 2, 3, 4, 5];
arr.copyWithin(0, 3); // copy from index 3 to the end, paste starting at index 0
console.log(arr); // [4, 5, 3, 4, 5]Best practices
- Use fill() combined with new Array(n) to quickly initialize a fixed-size array with default values before populating it
- Remember fill() and copyWithin() both mutate the array in place - copy first if the original needs to stay unchanged
- copyWithin() is rarely needed in typical application code - it is more common in performance-sensitive or lower-level array manipulation
- Double-check start/end index arguments carefully, as off-by-one mistakes are easy to make with these methods
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification