0

Why do we need to destructure Array(3) to produce a multidimensional array?

[...Array(3)].map(_=>Array(5).fill(0))       
/* output
(3) [Array(5), Array(5), Array(5)]
0 : (5) [0, 0, 0, 0, 0]
1 : (5) [0, 0, 0, 0, 0]
2 : (5) [0, 0, 0, 0, 0]
length: 3
*/

Array(3).map(_=>Array(5).fill(0))       
(3) [empty × 3]
length: 3
Akshay Vijay Jain
  • 13,461
  • 8
  • 60
  • 73
  • it has answer here https://stackoverflow.com/a/5501720/2761641 – Akshay Vijay Jain Nov 15 '22 at 17:23
  • 4
    `Array(3)` creates an array with 3 empty slots. `map()` does NOT iterate over empty slots. *"`callbackFn` is invoked only for array indexes which have assigned values. It is not invoked for empty slots in [sparse arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays)."* - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#description) I would personally use `Array.from({ length: 3 }, () => Array(5).fill(0))`, because I find it more descriptive, and as a result, better readable. – 3limin4t0r Nov 15 '22 at 17:27
  • 1
    If you're interested in why `[...Array(3)]` does work and `Array(3)` doesn't. Here is a quick answer. `Array(3)` could also be written as `[ , , ,]` (3 empty slots). Whereas `[...Array(3)]` uses the iterable protocol to produce values for the outer array. This protocol uses [`array.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/values#iterating_sparse_arrays) (technically the alias `array[Symbol.iterator]()`) which does iterate empty slots. Meaning that `[...Array(3)]` could also be written as `[undefined, undefined, undefined]` – 3limin4t0r Nov 15 '22 at 23:36
  • so ... i.e. spread operator uses iterator protocol and will iterate on empty slots as well, but .map does not use iterator so won't consider empty slots. Array(3) is same as Array(3).map(e=>({})) – Akshay Vijay Jain Nov 17 '22 at 06:21
  • I see the question linked above is asking the same thing, I previously thought it is different from my question, thus this can classify as a duplicate question – Akshay Vijay Jain Nov 17 '22 at 06:27

0 Answers0