JavaScript Array()
The Array() Constructor
The Array() constructor creates Array objects.
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(number) | Creates an array with the specified length and empty slots. |
| new Array(element) | Creates an array with one element, unless the element is a number. |
| 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.
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.
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"];
Object Hieraky
Array objects inherit from Object.
Object └─ Array
Array() Questions
| Question | Answer |
|---|---|
| Constructor Type | Function |
| Creates | Array objects |
| Inherits From | Object |
Browser Support
Array() is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |