The new Array() Constructor
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")
Try it Yourself »
Array()
Array(3)
Array("3")
Array("Saab", "Volvo", "BMW")
Try it Yourself »
| 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];
Try it Yourself »
The new keyword can produce some unexpected results:
// Create an array with three elements:
const points = new Array(40, 100, 1);
Try it Yourself »
// Create an array with two elements:
const points = new Array(40, 100);
Try it Yourself »
// Create an array with one element ???
const points = new Array(40);
Try it Yourself »
A Common Error
const points = [40];
is not the same as:
const points = new Array(40);
// Create an array with one element:
const points = [40];
Try it Yourself »
// Create an array with 40 undefined elements:
const points = new Array(40);
Try it Yourself »
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: