Emmanuel Akinfulubi

JavaScriptArray

Fill an array with a value in JavaScript

Beginner · 4 min read

Sometimes you need an array where every slot starts with the same value: a score board of zeros, a row of empty seats, a list of "not answered yet" flags. JavaScript has a method for exactly this, called fill.

In this tutorial you will fill a new array with zeros, fill just part of an existing array, and then find out why new Array(3).fill([]) almost never does what you want. You should know what an array and an index are. The rest is explained as we go.

What "mutate" means

Some array methods give you a new array and leave the old one alone. Others change the array you call them on. Changing an array in place is called mutating it. fill mutates: it writes into the array you already have, and then hands back that same array.

JavaScript

const a = [1, 2];
const b = a.fill(9);
console.log(a);       // [ 9, 9 ]
console.log(a === b); // true: one array, not two

=== on two arrays asks "are these the same array?", not "do they hold the same values?". Here the answer is yes.

Half-open ranges

fill can take a start and an end index. The start is included and the end is not. This is called a half-open range, and you will see it again in slice and substring. A quick way to remember it: end - start is how many slots get filled.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

2 Fill an array with a value

easy

Fill a new array with zeros, then fill only part of an existing one. Then work out why new Array(3).fill([]) is almost never what you want.

Stuck? Three hints, smallest first
  1. 1. fill(value) writes over every slot and returns the same array, mutated.
  2. 2. fill(value, start, end) takes a half-open range, and negative indexes count from the end.
  3. 3. fill writes the same value into every slot. For an object, that is one object shared by every slot.

Step 1: fill a new array

new Array(4) makes an array of length 4 with empty slots. fill(0) writes 0 into every one.

Step 1

const zeros = new Array(4).fill(0);
console.log(zeros); // [ 0, 0, 0, 0 ]

Because fill returns the array, you can create and fill it in one line.

Step 2: fill only part of an array

Give fill a start and an end to limit where it writes.

Step 2

const partial = [1, 2, 3, 4, 5].fill(0, 1, 3);
console.log(partial); // [ 1, 0, 0, 4, 5 ]

Indexes 1 and 2 became zero. Index 3 did not, because the end is left out. 3 - 1 is 2, and two slots changed.

Step 3: count from the end

A negative index counts back from the end of the array: -1 is the last slot, -2 the one before it. Leave out the end and fill goes all the way to the last slot.

Step 3

const tail = [1, 2, 3, 4].fill(0, -2);
console.log(tail); // [ 1, 2, 0, 0 ]

Step 4: the shared-array trap

Now say you want three empty lists, one per team. This looks right:

Step 4

const shared = new Array(3).fill([]);
shared[0].push('x');
console.log(shared);                  // [ [ 'x' ], [ 'x' ], [ 'x' ] ]
console.log(shared[0] === shared[2]); // true

You pushed into the first list only, yet all three changed. fill works out its value once. [] makes one array, and fill puts that same array into every slot. There are not three lists, there is one list seen from three places.

With numbers and strings you never notice this, because you can't change a number in place. With arrays, objects and Maps, it matters a lot.

Step 5: one new array per slot

To get a separate array in each slot, the code that makes the array has to run once per slot. Array.from({ length: 3 }, fn) calls fn for each slot, so each call builds a fresh array.

Step 5

const separate = Array.from({ length: 3 }, () => []);
separate[0].push('x');
console.log(separate); // [ [ 'x' ], [], [] ]

Only the first list changed. A function that makes a new value each time it is called is sometimes called a factory.

Step 6: a handy trick with fill()

Call fill() with nothing between the brackets and it writes undefined into every slot.

Step 6

const filled = [1, 2, 3].fill();
console.log(filled.every((v) => v === undefined)); // true
console.log(0 in filled);                           // true: the slot exists

That sounds useless, but it turns empty slots (holes) into real undefined values. Methods such as map skip holes, but they do visit real values, so new Array(3).fill().map(...) works where new Array(3).map(...) does not.

The full solution

The panel fills zeros, a middle range and a tail, then shows the shared array next to the factory version. Press Run and look at how many lists the push changed in each.

The answer

const zeros = new Array(4).fill(0);
const partial = [1, 2, 3, 4, 5].fill(0, 1, 3);         // indexes 1 and 2 only
const tail = [1, 2, 3, 4].fill(0, -2);                 // the last two

// One array object, referenced three times.
const shared = new Array(3).fill([]);
shared[0].push('x');

// A factory runs once per slot, so each slot gets its own array.
const separate = Array.from({ length: 3 }, () => []);
separate[0].push('x');

console.log('zeros   :', zeros);
console.log('partial :', partial, '<- fill(0, 1, 3) covers 1 and 2, not 3');
console.log('tail    :', tail);
console.log('--- one array, or three? ---');
console.log('fill([])       :', shared, '<- pushing into row 0 changed all three');
console.log('Array.from(...) :', separate);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('fill covers every slot', zeros, [0, 0, 0, 0]);
test('a range is half-open: start included, end excluded', partial, [1, 0, 0, 4, 5]);
test('negative indexes count from the end', tail, [1, 2, 0, 0]);
test('fill returns the same array, mutated', (() => { const a = [1, 2]; return a.fill(9) === a; })(), true);
test('fill([]) shares one array across every slot', shared, [['x'], ['x'], ['x']]);
test('because all three slots are the same object', shared[0] === shared[2], true);
test('a factory gives each slot its own', separate, [['x'], [], []]);
test('fill with no argument writes real undefined values, not holes', [1, 2, 3].fill().every((v) => v === undefined), true);
test('and those slots do exist', 0 in [1, 2, 3].fill(), true);

fill evaluates its argument once. With a number or a string that is invisible; with an object, an array or a Map it means every slot points at the same thing, and the assertion where pushing into row 0 changes rows 1 and 2 is what that looks like in practice. Use Array.from({ length: n }, () => []) whenever the filled value is a reference.

The last two assertions are the reason fill() with no argument is a useful trick: it converts holes into genuine undefined values, which map will then visit.

Common mistakes

  • Expecting the end index to be filled. fill(0, 1, 3) changes indexes 1 and 2 only.
  • Filling with [] or {}. Every slot gets the same object. Use Array.from({ length: n }, () => []) instead.
  • Forgetting that fill changes the original. If another part of your code holds the same array, it sees the new values too. Fill a copy ([...xs].fill(0)) if you need to keep the original.

Try it yourself

  1. Make an array of ten false values for a quiz with ten questions.
  2. Take ['a', 'b', 'c', 'd', 'e'] and replace the last three letters with '*'.
  3. Build three separate empty objects with Array.from, set a property on the first, and check that the other two stay empty.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.