The new Array() constructor creates an Array object.
Syntax
new Array()
new Array(number)
new Array(element1, element2, ..., elementN)
Array()
Array(number)
Array(element1, element2, ..., elementN)
Examples
new Array()
new Array(3)
new Array("3")
new Array("Saab", "Volvo", "BMW")
| Col 1 | Col 2 |
|---|---|
| Syntax | Description |
| new Array() | Creates an empty array. |
| new Array(x) | Creates an array with x empty spots. |
| new Array(elem1) | Creates an array with one element. |
| new Array(elem1,...,elemN) | Creates an array with multiple elements. |
The Difference? new Array() vs Array()
The short answer is: there is no functional difference between new Array() and Array().
Both commands do the exact same thing and create an array.
Note: The Array creator function is smart. It is programmed to check if you forgot the new keyword. If you leave it out, it adds it behind the scene.
JavaScript new Array()
JavaScript has a built-in array constructor new Array().
But you can most often use [] instead.
These two different statements both create a new empty array named points:
const points = new Array();
const points = [];
These two different statements both create a new array containing 6 numbers:
const points = new Array(40, 100, 1, 5, 25, 10);
const points = [40, 100, 1, 5, 25, 10];
The new keyword can produce some unexpected results:
// Create an array with three elements:
const points = new Array(40, 100, 1);
// Create an array with two elements:
const points = new Array(40, 100);
// Create an array with one element ???
const points = new Array(40);
A Common Error
const points = [40];
// Create an array with one element:
const points = [40];
// Create an array with 40 undefined elements:
const points = new Array(40);
Note: Important Warning Use an array literal [ ] instead of the new Array() when possible. new Array(number) is a special dangerous case. new Array(3) creates an array with 3 empty elements; not an array containing the number 3. Using [ ] is faster to type, easier to read, and avoids the "single number trap": For example, [3] actually creates [3], not [null,null,null].
Array Literal (Preferred)
The recommended way to create an array is with an array literal:
Example
const cars = ["Saab", "Volvo", "BMW"];
Note: Learn More: Array Tutorial Array Methods Array Search Methods Array Sort Methods Array Iteration Methods Full JavaScript Array Reference