Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.9 — Nested Arrays
JavaScript · Example 3 of 3

The fill trap when building a grid

fill([]) created one inner array and put it in every slot. Array.from calls the function once per row, so each row is new. Filling with "." is fine: strings are values, not shared objects.

An array can hold other arrays, which gives you grids and tables (2D arrays) read with two indexes like grid[row][col]; flat removes levels of nesting and flatMap maps and flattens one level in a single step.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Create a 3×3 multiplication table as a 2D array (table[r][c] is (r + 1) * (c + 1)) and print the middle row.

02

Given const orders = [["pen", "cap"], ["bag"], []];, make one list of all items and count them.

Explain it without notes

01

How do you read and loop over a 2D array?

02

Why does new Array(3).fill([]) cause bugs, and how do you build a grid correctly?

03

What is the difference between flat and flatMap?

04

How would you transpose a matrix in JavaScript?

The fill trap when building a grid

Console

(nothing was printed)

Expected console output

[ [ 'x' ], [ 'x' ], [ 'x' ] ]
true
[ [ 'x' ], [], [] ]
...
..#