How do you create and initialize a 2D two-dimensional array in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 6 days ago

How do you create and initialize a 2D two-dimensional array in JavaScript?

message-square
0

In JavaScript, a two-dimensional (2D) array is an array whose elements are themselves arrays. Because .fill([]) shares the exact same inner array reference across every row, the safest way to initialize a 2D grid of size rows × cols is Array.from() so each row gets its own independent array instance.


1. Initializing a 2D Array with Array.from() (Recommended)

Pass an outer length and a mapping callback that creates a fresh inner array per row:

function create2DArray(rows, cols, initialValue = 0) {
  return Array.from({ length: rows }, () =>
    Array.from({ length: cols }, () => initialValue)
  );
}

const grid = create2DArray(3, 4, 0);
grid[1][2] = 9;

console.log(grid[1][2]); // 9
console.log(grid[0][2]); // 0 (other rows are unaffected)

2. Literal Initialization and Dynamic / Computed Cells

For small fixed matrices, array literals are clear and readable. When cell values depend on row (r) or column (c) indices, pass (r, c) into the factory function:

// Literal 2D array (3x3)
const board = [
  ["X", null, "O"],
  [null, "X", null],
  ["O", null, null]
];

// Computed 2D multiplication table (4x4)
const table = Array.from({ length: 4 }, (_, r) =>
  Array.from({ length: 4 }, (_, c) => (r + 1) * (c + 1))
);

console.log(table[2][3]); // 12 (row index 2 -> 3, col index 3 -> 4)

3. Common Traps to Avoid

  • Using new Array(rows).fill(new Array(cols).fill(0)): Every row points to the same inner array reference—mutating grid[0][0] = 1 changes grid[1][0], grid[2][0], and every other row too.
  • Passing a shared object or array as initialValue: If initialValue is an object or array, wrap or clone it inside the inner generator (or use a factory function) so cells do not share mutable references.
  • Indexing [col][row] instead of [row][col]: Standard row-major indexing accesses the outer row index first and the inner column index second; staying consistent avoids out-of-bounds bugs on non-square grids.

TL;DR: Initialize 2D arrays with Array.from({ length: rows }, () => Array.from({ length: cols }, () => initialValue)) so each row is an independent array, and avoid .fill([]) which shares one inner array across all rows.

Are you building a fixed matrix, a grid initialized with computed coordinates, or a large numeric grid where a flat typed array might also be worth considering?