Multi-Dimensional Array
Example
const grid = new Array(3).fill(new Array(3).fill(0));
grid[0][0] = 1;const grid = Array.from({ length: 3 }, () => new Array(3).fill(0));
grid[0][0] = 1;fill() puts the same array object in every row; Array.from() with a callback builds a new row each time.
Common mistakes
- Changing one cell and seeing the whole column change, because every row is the same array.
Key points
- Rows are created with
Array.from()and a factory, notfill([]), which shares one row object. - Nested loops iterate rows in the outer loop and columns in the inner loop, matching
grid[row][col]. - Bounds checks test both
rowandcolbefore reading a neighbor cell.
Interview questions
How do I deep copy a 2D array?
Use grid.map((row) => [...row]) for numbers or strings, or structuredClone(grid) for nested objects.
Why does the order of nested loops matter for speed?
Reading row by row follows memory layout and is cache friendly. Column-first loops over large grids can be noticeably slower.
Can I store a 2D grid in a flat array?
Yes, use one array of size rows * cols and index it with row * cols + col. This is common with typed arrays.
