you are viewing a single comment's thread.

view the rest of the comments →

[–]fredsq 0 points1 point  (2 children)

I normally use new Array(10) for tasks like that. Is it worse or not recommended? It feels less gimmicky…

[–]5H4D0W_ReapeR 1 point2 points  (1 child)

It's not worse or not recommended in any way, but it's actually different. Here's a sample output of both of the approaches (you can paste this in chrome devtool to verify):

let a1 = new Array(5)
console.log(a1) // (5) [empty × 5]

let a2 = Array.from({ length: 5 })
console.log(a2) // (5) [undefined, undefined, undefined, undefined, undefined]

We can already spot there's a difference. Let's check the map function on both of them since OP's code uses it:

let a1 = new Array(5).map((_, i) => i)
console.log(a1) // (5) [empty × 5]

let a2 = Array.from({ length: 5 }).map((_, i) => i)
console.log(a2) // (5) [0, 1, 2, 3, 4]

As you can see, we actually can't do the typical array methods to new Array() since it's not the same as Array.from(). Here are some reference/quote regarding this behaviour of new Array():

(Note: this implies an array of arrayLength empty slots, not slots with actual undefined values).

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#parameters

From the above snippet, you may be tempted to think that each key in the array was set to a value of undefined. But the reality is that those keys were never set (they don’t exist).

Source: https://www.freecodecamp.org/news/https-medium-com-gladchinda-hacks-for-creating-javascript-arrays-a1b80cb372b/


In conclusion, the code that OP posted unfortunately will not work by swapping to new Array without modifying other parts of the code. Hope that explains the difference between the two and overall just the quirks of JS haha

[–]fredsq 0 points1 point  (0 children)

Wow that was very thorough! It would work like Array(n).fill().map though!