Whenever I work with arrays, I always use the []
style, however, when I want to create an array with a fixed amount of elements I use new Array(N)
(I don't know any other way of doing this)
I thought it wasn't big deal, until I read these strong words about this:
Anyone doing this, using “new Array()” instead of “[]“, or “new Object()” instead of “{}” needs to relearn JavaScript.
I really want to avoid writting bad code. Anyone mind tell me the right direction to go?
To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.
Another way to add/insert an element into an array is to use the . splice() method. With . splice() you can insert a new element at any given index, either overwriting what is currently in that index number, or inserting within, with no overwriting.
To create an array containing numbers from 1 to N:Create an empty array that will hold the numbers. Use a for loop to iterate N times, starting at 1 . For each iteration, push the loop's iteration index into the array.
Creating an ArrayUsing an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.
I wouldn't worry too much about some random comment on a blog in 2006. Especially since your use case isn't just new Array()
. You're using the special-case constructor that is provided specifically for this purpose.
Besides, using new Array()
instead of []
is hardly the worst thing someone can do with JS.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With