Codectionary / Developer documentation / JavaScript

fill() and copyWithin()

fill() changes all elements in an array (or a specified range) to a single static value, mutating the array in place - useful for initializing arrays. copyWithin() copies a sequence of elements to another position within the same array, also mutating in place, without changing the array's length.

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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation