How can I create a two dimensional array in JavaScript?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
JavaScript does not have a built-in matrix type for everyday array work, so a two-dimensional array is usually just an array of row arrays. The important part is not only how to create it, but how to avoid accidentally making every row refer to the same inner array.
Create a Two-Dimensional Array with Literals
If the values are known up front, the clearest solution is an array literal.
This is ideal for small fixed examples, test data, and board layouts that are easy to see directly in code.
Build It Dynamically with Array.from
When row and column counts come from variables, create each row separately.
This is one of the safest modern patterns because the callback creates a new inner array for every row.
Use Loops When Initialization Logic Is Custom
If each cell depends on row and column position, nested loops are often clearer than compressing everything into one expression.
This is also the easiest style to adapt when the default value is not constant.
Avoid the Shared-Row Trap
A common mistake is using fill with an array directly.
All rows change because every row points to the same inner array object. The correct version creates a fresh row each time.
That difference matters in grids, games, and table editing logic.
Access, Update, and Iterate Over the Data
You read and write cells using two indexes: one for the row and one for the column.
Iteration normally uses nested loops or higher-order array methods.
Choose the style that fits the transformation you need. Simple traversal often reads better with loops.
Consider Whether an Array of Objects Is Better
Not every table-like problem should use a numeric grid. If each row has named fields, an array of objects may be easier to maintain than a two-dimensional array where column meaning is implicit.
Two-dimensional arrays work best when the row-column structure itself is the core data model, such as matrices, boards, and pixel-like grids.
Common Pitfalls
- Using
Array(rows).fill(Array(cols).fill(value))and accidentally sharing every row. - Forgetting that row lengths can differ, because JavaScript arrays do not enforce rectangular shape.
- Choosing a matrix when an array of objects would make the data meaning clearer.
- Accessing indexes without checking bounds in dynamic grid code.
- Hiding custom initialization logic in one dense expression that is hard to debug later.
Summary
- A two-dimensional array in JavaScript is an array of arrays.
- Use literals for fixed data and
Array.fromfor dynamic rectangular grids. - Create each row separately to avoid shared references.
- Use nested loops when initialization depends on row and column position.
- Pick a different data structure when the data is record-shaped rather than grid-shaped.

