Array() constructor
The Array()
constructor creates Array
objects.
Syntax
new Array(element0, element1, /* … ,*/ elementN)
new Array(arrayLength)
Array(element0, element1, /* … ,*/ elementN)
Array(arrayLength)
Note: Array()
can be called with or without new
. Both create a new Array
instance.
Parameters
elementN
-
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the
Array
constructor and that argument is a number (see thearrayLength
parameter below). Note that this special case only applies to JavaScript arrays created with theArray
constructor, not array literals created with the bracket syntax. arrayLength
-
If the only argument passed to the
Array
constructor is an integer between 0 and 232 - 1 (inclusive), this returns a new JavaScript array with itslength
property set to that number (Note: this implies an array ofarrayLength
empty slots, not slots with actualundefined
values — see sparse arrays).
Exceptions
RangeError
-
Thrown if there's only one argument (
arrayLength
) and its value is not between 0 and 232 - 1 (inclusive).
Examples
Array literal notation
Arrays can be created using the literal notation:
const fruits = ["Apple", "Banana"];
console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
Array constructor with a single parameter
Arrays can be created using a constructor with a single number parameter. An array with
its length
property set to that number and the array elements are empty
slots.
const fruits = new Array(2);
console.log(fruits.length); // 2
console.log(fruits[0]); // undefined
Array constructor with multiple parameters
If more than one argument is passed to the constructor, a new Array
with
the given elements is created.
const fruits = new Array("Apple", "Banana");
console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"
Specifications
Specification |
---|
ECMAScript Language Specification # sec-array-constructor |
Browser compatibility
BCD tables only load in the browser
See also
Array
class