A tic-tac-toe board as a 2D array
Row first, then column. The diagonal is the cells where the row and column numbers are equal. columns is the board transposed.
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.
Create a 3×3 multiplication table as a 2D array (table[r][c] is (r + 1) * (c + 1)) and print the middle row.
Given const orders = [["pen", "cap"], ["bag"], []];, make one list of all items and count them.
Explain it without notes
How do you read and loop over a 2D array?
Why does new Array(3).fill([]) cause bugs, and how do you build a grid correctly?
What is the difference between flat and flatMap?
How would you transpose a matrix in JavaScript?
Preview
Console
Nothing logged yet.Expected console output
O
3 3
[ 'X', 'X', 'X' ] true
[ 'X', '', '' ]