Ad space (banner)
🟨JavaScript Lessons
Lesson 25 / 69

Two-Dimensional Arrays (Table-Shaped Data)

In this lesson you'll learn how to work with two-dimensional arrays in JavaScript so you can represent table-like or grid-like data. This is for people searching "JavaScript 2D array usage" or "JavaScript nested arrays."

Putting an array inside an array lets you represent a "table with rows and columns," a grid-like shape. This is called a two-dimensional array. You access it with two indices, like grid[row][column]. It's the basic idea behind representing a game board with coordinates, or spreadsheet-like data. Nest arrays inside arrays even further, and you can represent three-, four-, and higher-dimensional data structures too.

The sample code creates a 3x2 two-dimensional array called grid, and extracts the value at row 2, column 3 with grid[1][2]. Displaying each row with .join(",") inside a for...of loop is a commonly used pattern for making the contents of a two-dimensional array easy to check. Remember the order: specify the row first, then the column.

A common beginner stumbling block is reversing the order of the row and column indices. Writing grid[column][row] ends up accessing an unintended position. Also be careful when copying a two-dimensional array: using ... alone doesn't copy the inner arrays too (it's only a shallow copy).

In real development, two-dimensional arrays show up frequently in programs that handle grid-shaped data — image processing, managing a game's board, or importing spreadsheet-like data. This idea is also foundational in fields like data analysis and AI that rely on matrix operations.

When initializing a two-dimensional array, there's a pitfall where reusing and duplicating the same array causes every row to reference the same underlying array. Making sure to create a fresh array for each row is the trick to building a correct two-dimensional array.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)