At the time of array creation, the programmers need to specify the length of an array. It helps to allocate the proper amount of memory required to hold the array elements and ensures that the memory resources are effectively utilized and prevents potential overflow or memory faults.
This article will demonstrate the procedure for initializing the length of an array.
How to Initialize an Array Length in JavaScript?
For initializing the length of an array, use the “Array constructor” by passing a single argument which is the length of the array you want to create.
Syntax
For using the array constructor to initialize the length of an array, follow the given syntax:
Example
In the given example, create an array of length “11” using the Array constructor and store it in a variable “array”:
Print the array on the console:
It can be observed that an empty array of length “11” has been successfully created:
You can also initialize the array by passing elements in the constructor. It will create an array of a length of the specified elements:
As you can see that the created array is of the length “11” as the constructor contains 11 elements:
You can also create/declare an array and initialize its specific length by calling a custom function. Here, we will first define a function named “createArrayofSize()” that takes a size of an array as an argument. Then, create an empty array and append elements in it by iterating until the specified length. Finally, return the particular length’s array to the function:
var arr = [];
for (var i = 0; i < size; i++) {
arr[i] = i;
}
return arr;
}
Call the function by passing the length of an array:
Print the specified length’s array on the console:
Output
That was all about initializing the array length in JavaScript.
Conclusion
To initialize an array’s length, use the “Array constructor” as “new Array()” by passing a single argument which is the length of the array you want to create. You can also initialize the array by passing elements in the constructor such as “new Array(1, 2, 3)” or calling a custom function. In this article, we demonstrated the procedure for initializing the length of an array.