Array() Constructor
The Array
constructor in JavaScript is used to create arrays. It can be used to initialize an empty array, create an array with specified elements, or define the length of the array.
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)
Parameters
Parameter | Description |
---|---|
element1, element2, ..., elementN | Elements to include in the new array. Each element will become an item in the array. |
arrayLength | An integer specifying the length of the array. The array will be created with this length but without any elements. |
Return Value
The Array
constructor creates a new array. Depending on the parameters provided, the array may contain elements or be empty with a specified length.
Examples
1. Creating an Empty Array
An empty array can be created using the Array
constructor without any arguments.
const emptyArray1 = new Array();
const emptyArray2 = Array();
console.log(emptyArray1); // []
console.log(emptyArray2); // []
Output
[]
[]
2. Creating an Array with Specific Elements
This example demonstrates how to create an array with specific elements.
const array1 = new Array(1, 2, 3);
const array2 = Array('a', 'b', 'c');
console.log(array1); // [1, 2, 3]
console.log(array2); // ['a', 'b', 'c']
Output
[1, 2, 3]
['a', 'b', 'c']
new Array(1, 2, 3)
creates an array with three elements:1
,2
, and3
.Array('a', 'b', 'c')
creates an array with three string elements.
3. Creating an Array with a Specified Length
You can create an array with a specified length, but it will not contain any elements initially.
const arrayWithLength1 = new Array(5);
const arrayWithLength2 = Array(3);
console.log(arrayWithLength1); // [empty × 5]
console.log(arrayWithLength2); // [empty × 3]
Output
[ <5 empty items> ]
[ <3 empty items> ]
These arrays are empty but have a defined length. The length property is set, but the indices are uninitialized.
4. Avoiding Ambiguity Between Length and Elements
If only one numeric argument is provided to the Array
constructor, it is treated as the array’s length. To create an array with a single numeric element, use square brackets or pass multiple arguments.
const array1 = new Array(5); // Creates an empty array with length 5
const array2 = [5]; // Creates an array with one element: 5
const array3 = Array(1, 2, 3); // Creates an array with elements 1, 2, and 3
console.log(array1); // [empty × 5]
console.log(array2); // [5]
console.log(array3); // [1, 2, 3]
Output
[ <5 empty items> ]
[5]
[1, 2, 3]