Creating an array
The following statements create equivalent arrays:
const arr1 = new Array(element0, element1, /* …, */ elementN);
const arr2 = Array(element0, element1, /* …, */ elementN);
const arr3 = [element0, element1, /* …, */ elementN];
element0, element1, …, elementN is a list of values for the array's elements. When these values are specified, the array is initialized with them as the array's elements. The array's length property is set to the number of arguments.
The bracket syntax is called an "array literal" or "array initializer." It's shorter than other forms of array creation, and so is generally preferred. See Array literals for details.
To create an array with non-zero length, but without any items, either of the following can be used:
// This...
const arr1 = new Array(arrayLength);
// … results in the same array as this
const arr2 = Array(arrayLength);
// This has exactly the same effect
const arr3 = [];
arr3.length = arrayLength;
Note:
In the above code, arrayLength must be a Number. Otherwise, an array with a single element (the provided value) will be created. Calling arr.length will return arrayLength, but the array doesn't contain any elements. A for...in loop will not find any property on the array.
In addition to a newly defined variable as shown above, arrays can also be assigned as a property of a new or an existing object:
const obj = {};
// …
obj.prop = [element0, element1, /* …, */ elementN];
// OR
const obj = { prop: [element0, element1, /* …, */ elementN] };
If you wish to initialize an array with a single element, and the element happens to be a Number, you must use the bracket syntax. When a single Number value is passed to the Array() constructor or function, it is interpreted as an arrayLength, not as a single element.
This creates an array with only one element: the number 42.
const arr = [42];
This creates an array with no elements and arr.length set to 42.
const arr = Array(42);
This is equivalent to:
const arr = [];
arr.length = 42;
Calling Array(N) results in a RangeError, if N is a non-whole number whose fractional portion is non-zero. The following example illustrates this behavior.
const arr = Array(9.3); // RangeError: Invalid array length
If your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. Alternatively, create an empty array first before adding the single element to it.
You can also use the Array.of static method to create arrays with single element.
const arr = Array.of(9.3); // arr contains only one element 9.3