Let's assume that we want to declare a 2-dimensional array (length = 5) in JavaScript.
javascript// 🔴 Wrong approach to create a 2-dimensional array let array = Array(5).fill([]); // It looks good on paper console.log(array); /* (5) [Array(0), Array(0), Array(0), Array(0), Array(0)] 0: [] 1: [] 2: [] 3: [] 4: [] length: 5 __proto__: Array(0) */ // But let's say we want to push an element into it // E.g. at index = 2 array[2].push('Erik'); // Let's print the result console.log(array); /* (5) [Array(1), Array(1), Array(1), Array(1), Array(1)] 0: ["Erik"] 1: ["Erik"] 2: ["Erik"] 3: ["Erik"] 4: ["Erik"] length: 5 __proto__: Array(0) */
Oops! The problem with this approach is that after pushing the element, it's replicating in all the positions of the array.
When we fill the array with []
, we are passing the same array reference to each position. As we want independent arrays, we could create the 2-dimensional array like this:
javascript// ✅ Create a 2-dimensional array using ES6 // .map is returning 5 new arrays let array = Array(5).fill(0).map(elem => []); // Now we can push an element without any troubles array[2].push('Erik'); // Let's print the result console.log(array); /* (5) [Array(0), Array(0), Array(1), Array(0), Array(0)] 0: [] 1: [] 2: ["Erik"] 3: [] 4: [] length: 5 __proto__: Array(0) */
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.