Multidimensional Arrays in JavaScript

Introduction

A matrix or grid is an array of arrays—rows and columns for games, spreadsheets, and image pixels. JavaScript has no special matrix type; you nest arrays and access grid[row][col]. This chapter builds 2D structures, iterates them, and notes shallow-copy pitfalls.

Prerequisites

2D Array Basics

javascript
// 3 rows, each row is an array
const grid = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];
 
console.log(grid[0][2]);
console.log(grid[2][1]);

Row index first, column second: grid[row][col].

Creating a Grid

javascript
// Build empty 3x3 board
const rows = 3;
const cols = 3;
const board = [];
 
for (let r = 0; r < rows; r++) {
  const row = [];
  for (let c = 0; c < cols; c++) {
    row.push(null);
  }
  board.push(row);
}
 
console.log(board);

Warning

Array(3).fill([]) creates one shared row reference repeated three times—mutating grid[0][0] affects all rows. Build rows in a loop or Array.from.

Iterating All Cells

javascript
// Nested for-of
const matrix = [
  ["a", "b"],
  ["c", "d"],
];
 
for (const row of matrix) {
  for (const cell of row) {
    console.log(cell);
  }
}

With indexes:

javascript
// Row and column indices
for (let r = 0; r < matrix.length; r++) {
  for (let c = 0; c < matrix[r].length; c++) {
    console.log(`(${r},${c})`, matrix[r][c]);
  }
}

Jagged Arrays

Rows can have different lengths:

javascript
// Triangle shape
const triangle = [
  [1],
  [2, 3],
  [4, 5, 6],
];
 
console.log(triangle[2].length);

flat and flatMap

javascript
// Flatten one level
const nested = [1, [2, 3], [4, [5]]];
console.log(nested.flat());
console.log(nested.flat(2));

Mini Example: Tic-Tac-Toe Cell

javascript
// 3x3 game board
const game = [
  [" ", " ", " "],
  [" ", " ", " "],
  [" ", " ", " "],
];
 
function place(row, col, mark) {
  if (game[row][col] !== " ") return false;
  game[row][col] = mark;
  return true;
}
 
place(1, 1, "X");
console.log(game[1][1]);

FAQ

Are 2D arrays common in JS?

Yes for games and tables; databases and APIs often prefer flat arrays plus width/height metadata.

How do I deep-clone a matrix?

structuredClone(grid) or map rows: grid.map((row) => [...row]).

3D arrays?

Same pattern: cube[z][y][x]—arrays all the way down.

What comes next?

Functions in JavaScript—reusable logic blocks.