JavaScript Array()
The Array() constructor creates an Array object.
Array objects are used to store multiple values in a single variable.
Syntax
new Array()
new Array(element1)
new Array(element1, element2, ..., elementN)
new Array(arrayLength)
Array()
Array(element1)
Array(element1, element2, ..., elementN)
Array(arrayLength)
Explanation
| Syntax | Description |
|---|---|
| new Array() | Creates an empty array. |
| new Array(element) | Creates an array with one element, unless the element is a number. |
| new Array(number) | Creates an array with the specified length and empty slots. |
| new Array(element1, ..., elementN) |
Creates an array with the specified elements. |
Important Warning
Use array literals instead of the Array() constructor when possible.
new Array(3) creates an empty array with length 3, not an array containing the number 3.
Object Hieraky
Array objects inherit from Object.
Object └─ Array
| Constructor Type | Function |
| Creates | Array objects |
| Inherits From | Object |
Example
const cars = new Array("Saab", "Volvo", "BMW");
One Number Argument
const points = new Array(3);
document.getElementById("demo").innerHTML = points.length;
One Non-Number Argument
const points = new Array("3");
document.getElementById("demo").innerHTML = points;
Array Literal (Preferred)
The recommended way to create an array is with an array literal:
Example
const cars = ["Saab", "Volvo", "BMW"];
Browser Support
new Array() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |