Algorithms and Data Structures · Junior · Question 70 of 75

Why should you avoid new Array(3).fill([]) for a 3 × 3 grid?

const grid = new Array(3).fill([]);
grid[0].push(1);

Explanation

fill puts the same object reference into every slot, so grid[1] and grid[2] also get the 1. Create separate rows instead: Array.from({ length: 3 }, () => []).

Further reading

Problem with a question

Algorithms and Data Structures · Junior · question 70

Test yourself

Take the Algorithms and Data Structures · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz