docs.rodeo

MDN Web Docs mirror

Array() constructor

{{JSRef}} 

The Array() constructor creates {{jsxref("Array")}}  objects.

Syntax

new Array()
new Array(element1)
new Array(element1, element2)
new Array(element1, element2, /* …, */ elementN)
new Array(arrayLength)

Array()
Array(element1)
Array(element1, element2)
Array(element1, element2, /* …, */ elementN)
Array(arrayLength)

Note: Array() can be called with or without new. Both create a new Array instance.

Parameters

Exceptions

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 is created with its length property set to that number, and the array elements are empty slots.

const arrayEmpty = new Array(2);

console.log(arrayEmpty.length); // 2
console.log(arrayEmpty[0]); // undefined; actually, it is an empty slot
console.log(0 in arrayEmpty); // false
console.log(1 in arrayEmpty); // false
const arrayOfOne = new Array("2"); // Not the number 2 but the string "2"

console.log(arrayOfOne.length); // 1
console.log(arrayOfOne[0]); // "2"

Array constructor with multiple parameters

If more than one argument is passed to the constructor, a new {{jsxref("Array")}}  with the given elements is created.

const fruits = new Array("Apple", "Banana");

console.log(fruits.length); // 2
console.log(fruits[0]); // "Apple"

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN