In this tutorial, you will learn how to get the length of an array. In addition, we gonna create an array of any given length.
One such property is ‘length‘. With the help of this property, you can get the array length.
// given array let array = [1,2,1,4,5]; console.log(array.length); //5
The value returned by the length property is a positive integer.
You can also create an array of certain lengths. To create an array of specified length we have to create an array object/instance of the Array class using a new keyword. And finally, pass a positive integer value to the constructor.
Below is the code example.
// create a aray length let array = new Array(10); console.log(array.length); //10
Note: The maximum size of the array you can create is less than 4294967296, i.e 2^32.
Case 1: What if we pass a negative length to the constructor?
Case 2: What if we create an array length of 2^32?
// negative array length let array = new Array(-1); console.log(array.length); // for 2^32 array length size let anotherArray = new Array (4294967296); console.log(anotherArray.length);
As expected it generates an error message for both the above cases: RangeError: Invalid array length
Thus, the max length of the array you can create is (2^32) -1 that is 4294967295.
Uses of the array length property
- Use length value to iterate over an array.
- Create an empty array of fixed lengths.
- Also, the array length property can be used to shrink, expand and clear an array.