What does fill() do in JavaScript?
Short answer: array.fill(value, start, end) replaces the items of an array with the same value and returns the same array. It is the quickest way to create an array with a starting value: new Array(3).fill(0) gives [0, 0, 0].
new Array(3).fill(0); // [0, 0, 0]
[1, 2, 3, 4, 5].fill(0, 1, 3); // [1, 0, 0, 4, 5]fill() changes the original array. With objects or arrays, every position gets the same object, so use Array.from() when each position needs its own.
fill() writes the same value in every position or in a range, and with objects every position points to the same one.
fill() at a glance
| What you want | Code | Result |
|---|---|---|
| An array of zeros | new Array(3).fill(0) | [0, 0, 0] |
| Replace a range | [1, 2, 3, 4, 5].fill(0, 1, 3) | [1, 0, 0, 4, 5] |
| Replace the last item | [1, 2, 3].fill(9, -1) | [1, 2, 9] |
| A string repeated | new Array(3).fill("x").join("") | "xxx" (or "x".repeat(3)) |
| Numbers 0, 2, 4 | Array(3).fill().map((_, i) => i * 2) | [0, 2, 4] |
| An array of empty arrays | Array.from({ length: 2 }, () => []) | [[], []], each one different |
| A 2D grid | Array.from({ length: 2 }, () => Array(3).fill(0)) | [[0, 0, 0], [0, 0, 0]] |
| A typed array | new Uint8Array(4).fill(255) | [255, 255, 255, 255] |
Syntax of fill()
array.fill(value)
array.fill(value, start)
array.fill(value, start, end)value: what you put in each position.start(optional): the first position to fill. By default0.end(optional): where to stop. This position is not filled. By default, the length of the array.
Negative numbers count from the end, so -1 is the last position. fill() returns the same array it changed, so a.fill(0) === a is true.
