Skip to main content

What is a two-dimensional array?

A two-dimensional array (or array of arrays) is a data structure in which each element is itself an array.

Put simply, it is a table: rows and columns, like in Excel or a matrix.


Example of a two-dimensional array:

javascript
const matrix = [ [1, 2, 3], // ← row 0 [4, 5, 6], // ← row 1 [7, 8, 9] // ← row 2 ];

Here:

  • matrix[0] → [1, 2, 3] (the first row)
  • matrix[1][2] → 6 (an element from the second row, third column)

Visually:

javascript
[ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
012
0123
1456
2789

How to access elements

javascript
console.log(matrix[0][0]); // 1 console.log(matrix[2][1]); // 8

The first index is the row, the second is the column.


How to iterate over all elements

With nested loops:

javascript
for (let i = 0; i < matrix.length; i++) { for (let j = 0; j < matrix[i].length; j++) { console.log(matrix[i][j]); } }
  • i is the row number,
  • j is the column number.

Example use case:

Two-dimensional arrays are often used for:

  • storing tables and matrices of numbers;
  • representing game boards (for example, chess, tic-tac-toe);
  • storing coordinates (x, y);
  • working with images, pixels, grids, and so on.

Creating an empty two-dimensional matrix:

javascript
const rows = 3; const cols = 4; const matrix = Array.from({ length: rows }, () => Array(cols).fill(0)); console.log(matrix); /* [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] */

In short:

TermMeaning
Two-dimensional arrayAn array where each element is an array
Indexing[row][column]
Examplematrix[1][2] → 6
Often used forTables, grids, coordinates, matrices

Summary: A two-dimensional array is a "table in code": an array made up of other arrays. It lets you conveniently store data as rows and columns.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.