The Array()
constructor is used to create Array
objects.
Syntax
[element0, element1, ..., elementN] new Array(element0, element1[, ...[, elementN]]) new Array(arrayLength)
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 the arrayLength 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). If the argument is any other number, aRangeError
exception is thrown.
Examples
Array literal notation
Arrays can be created using the literal notation:
let 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.
let 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.
let fruits = new Array('Apple', 'Banana'); console.log(fruits.length); // 2 console.log(fruits[0]); // "Apple"
Specifications
Specification |
---|
ECMAScript (ECMA-262) The definition of 'Array constructor' in that specification. |
Browser compatibility
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Array() constructor | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 4 | Opera Full support 4 | Safari Full support 1 | WebView Android Full support ≤37 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support 10.1 | Safari iOS Full support 1 | Samsung Internet Android Full support 1.0 | nodejs Full support 0.1.100 |
Legend
- Full support
- Full support
See also
Array
class