Standard array initialization
suggest changeThere are many ways to create arrays. The most common are to use array literals, or the Array constructor:
const arr = [1, 2, 3, 4];
const arr2 = new Array(1, 2, 3, 4);
If the Array constructor is used with no arguments, an empty array is created.
const arr3 = new Array();
results in:
[]
If it is called with exactly one argument and that argument is an integer in range, the result has that length and no elements. Reading a missing element yields undefined, but the index is not present. A fractional, negative, or out-of-range number throws RangeError.
const arr4 = new Array(4);
arr4.length; // 4
0 in arr4; // false
That does not apply if the single argument is non-numeric:
const arr5 = new Array("foo");
results in:
["foo"]
Similar to an array literal, Array.of can be used to create a new Array instance given a number of arguments:
Array.of(21, "Hello", "World");
results in:
[21, "Hello", "World"]
In contrast to the Array constructor, creating an array with a single number such as Array.of(23) will create a new array [23], rather than an Array with length 23.
The other way to create and initialize an array would be Array.from
const newArray = Array.from({ length: 5 }, (_, index) => Math.pow(index, 4));
will result:
[0, 1, 16, 81, 256]