4Geeks chosen to deliver AI education in the Bahamas alongside Harvard, Oxford, and Columbia.See more

How to use the Javascript Fill Method?

By 4Geeks

Fill an array or a range with one value, create arrays with a starting value and avoid the shared-reference trap with objects.

6 min readLast updated
JavaScript array fill() icon

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].

javascript
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 wantCodeResult
An array of zerosnew 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 repeatednew Array(3).fill("x").join("")"xxx" (or "x".repeat(3))
Numbers 0, 2, 4Array(3).fill().map((_, i) => i * 2)[0, 2, 4]
An array of empty arraysArray.from({ length: 2 }, () => [])[[], []], each one different
A 2D gridArray.from({ length: 2 }, () => Array(3).fill(0))[[0, 0, 0], [0, 0, 0]]
A typed arraynew Uint8Array(4).fill(255)[255, 255, 255, 255]

Syntax of fill()

javascript
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 default 0.
  • 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.

Career · AI Engineering for Developers

You already master JavaScript arrays, now build AI apps with them

Use the coding skills you already have to build AI agents, RAG systems and LLM-powered apps, with mentors and real projects.

Create an array with a starting value

new Array(3) creates an array with 3 empty slots. Methods like map() skip empty slots, so fill it first:

javascript
console.log(new Array(3));                     // [ <3 empty items> ]
console.log(new Array(3).map(() => 1));        // [ <3 empty items> ]
console.log(new Array(3).fill(null).map(() => 1)); // [1, 1, 1]

Array.from() does the same in one step and gives you the position:

javascript
Array.from({ length: 3 }, (_, i) => i + 1);    // [1, 2, 3]
[...Array(3).keys()];                          // [0, 1, 2]

Fill only part of an array

javascript
const seats = ["free", "free", "free", "free", "free"];
 
seats.fill("taken", 1, 3);
console.log(seats);   // ["free", "taken", "taken", "free", "free"]
 
seats.fill("taken", -1);
console.log(seats);   // ["free", "taken", "taken", "free", "taken"]

Remember that end is not included: fill("taken", 1, 3) changes positions 1 and 2.

fill() with objects and arrays: the shared reference

With an object or an array, fill() doesn't make copies. It puts the same reference in every position, so changing one changes all of them:

javascript
const rows = new Array(2).fill([]);
rows[0].push(1);
console.log(rows);    // [[1], [1]]
 
const users = new Array(2).fill({ score: 0 });
users[0].score = 5;
console.log(users);   // [{ score: 5 }, { score: 5 }]

To get a different object in each position, create it inside a function with Array.from():

javascript
const rows = Array.from({ length: 2 }, () => []);
rows[0].push(1);
console.log(rows);    // [[1], []]

Create a 2D grid or matrix

javascript
const grid = Array.from({ length: 2 }, () => Array(3).fill(0));
grid[0][1] = 1;
console.log(grid);    // [[0, 1, 0], [0, 0, 0]]

The inner fill(0) is safe because 0 is a number, not an object. Avoid Array(2).fill(Array(3).fill(0)): both rows would be the same array.

The same rule applies to function calls: Array(3).fill(Math.random()) calls Math.random() once and repeats that number. Use Array.from({ length: 3 }, () => Math.random()) for three different values.

fill() vs Array.from() vs map()

fill()Array.from()map()
Changes the original arrayYesNo, creates a new oneNo, creates a new one
Same value in every positionYesWith () => valueWith () => value
Value depends on the positionNoYes, (_, i) => ...Yes, (x, i) => ...
A new object in each positionNoYesYes
Works with empty slotsYesYesNo, skips them

Use AI to work with fill()

An assistant like ChatGPT, Claude or GitHub Copilot can write the array you need and explain a surprising result. These three prompts are ready to copy.

1. Create an array

In JavaScript, I need an array of [length] items where each item is [describe it].
Show me how to create it with fill() or Array.from() and explain which one fits better.

2. Explain a result

This JavaScript code: [paste your code]
prints [what you see] and I expected [what you expected].
Explain why and how to fix it.

3. Build a grid

I want a [rows] x [columns] grid in JavaScript for [a game board / a seating plan / ...],
starting with [value] in every cell. Show me how to create it and change one cell.

Check the result with console.log() and change one item to make sure the positions are independent.

Learn with a mentor

From array methods to shipping AI features

In the 4Geeks AI Engineering for Developers program you add AI agents, RAG and production LLM apps to your portfolio.

Common problems with fill()

What you seeWhy it happensFix
Changing one row changes all of themfill([]) or fill({}) shares one referenceArray.from({ length: n }, () => [])
map() does nothing on new Array(3)The slots are empty and map() skips themnew Array(3).fill(null).map(...) or Array.from()
The last position isn't filledend is not includedUse end one higher, or leave it out
The original array changedfill() changes the array in placeCopy it first: [...arr].fill(0)
Array(3).fill(Math.random()) repeats one numberThe value is calculated onceArray.from({ length: 3 }, () => Math.random())
TypeError: Cannot assign to read only property '0'The array is frozenCopy it before you fill it
RangeError: Invalid array lengthnew Array(-1) or a length that isn't a whole numberCheck the length before creating the array
Free download

JavaScript fill() in a 2-page cheat sheet

fill() with start and end, recipes for starting arrays, the shared-reference trap, 2D grids, empty slots, common errors and prompts for ChatGPT, Claude or Copilot. Free, in PDF.

JavaScript array fill() cheat sheet

2 pages · PDF · 4Geeks

  • fill() and Array.from() recipes ready to copy
  • How to avoid the shared-reference trap with objects
  • Common errors and prompts to solve them with AI

Get it free

Your PDF right away

Frequently asked questions about JavaScript array fill()

Want to go from array methods to building AI apps, with real projects and mentors?

See the AI Engineering for Developers program