JavaScript Array Constructor Property returns the array objects. We can create empty array using array() constructor without passing parameters. We can create an array of given size using array(arrayLength) constructor with a passing parameters arrayLength. Also, we can create an array of size N by passing N elements to the array constructor.
Syntax
// Create an empty array of size 0
let emptyArr = new Array();
// Create an array of size N with given elements
let arr = new Array(element1, element2, /* …, */ elementN);
// Create an array of size arrayLength
// with undefined values
let arr = new Array(arrayLength);
Parameters
Parameter | Description |
---|---|
element1, element2, /* …, */ elementN | These Array elements are used to initialize the array. |
arrayLength | It defines the array length and its range is between 0 to 232 – 1. It returns an array of size length. |
Return Value
Return Type | Description |
---|---|
Array Object | It returns an array object that contains the give array elements. If array constructor does not contain any values then it returns empty array of size 0. |
It returns an array object of size length with values undefined. |
Example 1: Array Constructor without Parameter
This code creates an empty array using the Array constructor and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = new Array(); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array:
Array Size: 0
Example 2: Array Constructor with one Parameter
This code creates an array with a single element “Welcome” using the Array constructor and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = new Array("Welcome"); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array: Welcome
Array Size: 1
Example 3: Array Constructor with Multiple Parameters
This code creates an array with the elements 1, 3, 4, 6, and 8 using the Array constructor and assigns it to the variable arr. It then prints the array and its size to the console.
let arr = new Array(1, 3, 4, 6, 8); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array: 1,3,4,6,8
Array Size: 5
Example 4: Array Constructor to Create Empty Array of Size N
This code creates an empty array with a length of 5 using the Array constructor and assigns it to the variable arr. The array contains five empty slots but no actual elements.
// Create empty array of size 5 let arr = new Array(5); console.log("Array: " + arr); console.log("Array Size: " + arr.length);
Output
Array: ,,,,
Array Size: 5
Browsers Compatibility
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |