Emmanuel Akinfulubi

JavaScriptArray

Create a 2D array (grid) in JavaScript

Intermediate · 4 min read

A grid is a table of rows and columns: a tic-tac-toe board, a seating plan, a spreadsheet, the tiles in a game map. In JavaScript you store a grid as an array of rows, where each row is itself an array. That is called a 2D array (two-dimensional).

In this tutorial you will write grid(rows, cols, value), which builds a grid filled with one value. The important part is that writing to one cell must change exactly one cell. There is a popular one-liner that gets this wrong, and you will see exactly why. You should know what an array is and how arrow functions look. Array.from and ?. are explained below.

Reading and writing a cell

In a 2D array, the first index picks the row and the second picks the column inside it.

JavaScript

const board = [
  ['a', 'b'],
  ['c', 'd'],
];
console.log(board[1][0]); // 'c': row 1, column 0
board[0][1] = 'X';
console.log(board[0]);    // [ 'a', 'X' ]

Same array, or just equal?

=== on two arrays asks "are these the very same array in memory?". Two arrays with the same contents are still two different arrays.

JavaScript

console.log([0, 0] === [0, 0]); // false
const row = [0, 0];
console.log(row === row);       // true

Keep this in mind. A grid is only safe if every row is a different array.

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

5 A grid, without accidentally sharing a row

fair

Build a rows × cols grid of zeros so that writing to one cell changes exactly one cell. Show what goes wrong with new Array(rows).fill(new Array(cols).fill(0)).

Stuck? Three hints, smallest first
  1. 1. The outer array must be built with a factory, so the inner array is created once per row.
  2. 2. Array.from({ length: rows }, () => ...) calls its mapper once per slot.
  3. 3. Write to grid[0][0] and then read grid[1][0]. That single check tells you which version you have.

Step 1: the tempting one-liner

fill writes one value into every slot of an array. So this looks like a quick way to make a 2 by 2 grid of zeros:

Step 1

const shared = new Array(2).fill(new Array(2).fill(0));
shared[0][0] = 9;
console.log(shared);                  // [ [ 9, 0 ], [ 9, 0 ] ]
console.log(shared[0] === shared[1]); // true

We changed one cell, row 0 column 0, but row 1 changed as well. The inner new Array(2).fill(0) runs only once and makes one row. fill then puts that same row into both slots. There is one row, seen from two places, so a change to "one" row is a change to both.

Step 2: build each row separately

Array.from({ length: n }, fn) makes an array of length n and calls fn once per slot. If fn creates a new array, every slot gets its own.

Step 2

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

Each call to the arrow function writes a fresh [0, 0], so the two rows are separate.

Step 3: make it a function

Now replace the fixed [0, 0] with a second Array.from that builds cols cells, and let the caller choose the value.

Step 3

const grid = (rows, cols, value = 0) =>
  Array.from({ length: rows }, () => Array.from({ length: cols }, () => value));
const good = grid(2, 2);
good[0][0] = 9;
console.log(good);          // [ [ 9, 0 ], [ 0, 0 ] ]
console.log(grid(2, 3));    // [ [ 0, 0, 0 ], [ 0, 0, 0 ] ]

The outer Array.from runs the inner one once for every row, so there are as many separate row arrays as there are rows. Writing to good[0][0] changes one cell. That single check, write to [0][0] and read [1][0], tells you which kind of grid you have.

Step 4: use the indexes

The function you pass to Array.from also gets the index. Use the row index r and column index c to fill each cell with something different, like a cell number.

Step 4

const coords = Array.from({ length: 2 }, (_, r) =>
  Array.from({ length: 3 }, (_, c) => r * 3 + c));
console.log(coords);       // [ [ 0, 1, 2 ], [ 3, 4, 5 ] ]
console.log(coords[1][2]); // 5

r * 3 + c numbers the cells left to right, top to bottom. The _ is a name for the first argument, which we don't use.

Step 5: reading outside the grid

If you read a row that isn't there, you get undefined. Asking for a column of undefined is an error.

Step 5

const coords = [[0, 1, 2], [3, 4, 5]];
try {
  coords[9][0];
} catch (e) {
  console.log(e.constructor.name); // TypeError
}
console.log(coords[9]?.[0]);       // undefined

?. is optional chaining. It means "if the left side is null or undefined, stop and give undefined instead of carrying on". With ?.[0], a missing row gives a blank answer instead of crashing your program.

Step 6: the edges

Step 6

const grid = (rows, cols, value = 0) =>
  Array.from({ length: rows }, () => Array.from({ length: cols }, () => value));
console.log(grid(0, 3)); // []
console.log(grid(2, 0)); // [ [], [] ]

Zero rows gives an empty array. Zero columns gives the right number of rows, each with nothing in it.

The full solution

The panel builds a safe grid and the shared one side by side, writes 9 into the first cell of each, and prints both. Press Run and see which one changed a whole column.

The answer

const grid = (rows, cols, value = 0) =>
  Array.from({ length: rows }, () => Array.from({ length: cols }, () => value));

const good = grid(2, 2);
good[0][0] = 9;

// One inner array, referenced by every row.
const shared = new Array(2).fill(new Array(2).fill(0));
shared[0][0] = 9;

// Indexes are available if the mapper wants them: row, then column.
const coords = Array.from({ length: 2 }, (_, r) =>
  Array.from({ length: 3 }, (_, c) => r * 3 + c));

console.log('good   :', good, '<- one cell changed');
console.log('shared :', shared, '<- both rows changed');
console.log('same object?', shared[0] === shared[1]);
console.log('coords :', coords);
console.log('reading a cell:', coords[1][2], ' out of range:', coords[9]?.[0]);

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('the shape is rows of columns', grid(2, 3), [[0, 0, 0], [0, 0, 0]]);
test('writing one cell changes one cell', good, [[9, 0], [0, 0]]);
test('fill() with an array shares it across every row', shared, [[9, 0], [9, 0]]);
test('because the rows are the same object', shared[0] === shared[1], true);
test('while the factory rows are distinct', good[0] === good[1], false);
test('the mapper can compute from the indexes', coords, [[0, 1, 2], [3, 4, 5]]);
test('zero rows is an empty array', grid(0, 3), []);
test('zero columns is rows of nothing', grid(2, 0), [[], []]);
test('a missing row needs guarding, not indexing twice', coords[9]?.[0], undefined);

This is exercise 2's sharing trap in the shape it usually appears: a grid where writing one cell changes a whole column. fill takes one value and writes that same reference everywhere, so new Array(2).fill(new Array(2).fill(0)) builds one row and points both slots at it.

The last assertion is worth keeping. coords[9][0] throws, because coords[9] is undefined; coords[9]?.[0] gives undefined. On a grid read from user input, that one ?. is the difference between a blank cell and a crash.

Common mistakes

  • Using fill with an array. new Array(r).fill(new Array(c).fill(0)) shares one row. Build each row with Array.from and a function.
  • Mixing up the order of the indexes. grid[row][col] is the usual order. If you think in x and y, x is the column: grid[y][x].
  • Reading a missing row. grid[9][0] throws. Use grid[9]?.[0] when the row might not exist.

Try it yourself

  1. Build a 3 by 3 tic-tac-toe board filled with '.', put an 'X' in the middle, and print it.
  2. Build a 10 by 10 times table where table[r][c] is (r + 1) * (c + 1).
  3. Write countCells(grid, value) that counts how many cells equal value.

Keep practising

Newsletter

New writing, when it lands.

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