JavaScript

How to Initialize an Array’s Length in JavaScript

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:

new Array(len)

 
Example

In the given example, create an array of length “11” using the Array constructor and store it in a variable “array”:

let array = new Array(11);

 
Print the array on the console:

console.log(array);

 
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:

let array = new Array(1, 3, 35, 4, 2, 27, 91, 3, 4, 5, 12);

 
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:

function createArrayofSize(size) {
 var arr = [];
 for (var i = 0; i < size; i++) {
  arr[i] = i;
 }
 return arr;
}

 
Call the function by passing the length of an array:

var array = createArrayofSize(11);

 
Print the specified length’s array on the console:

console.log(array);

 
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.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.