For many of you, JavaScript is the very first language to get started with. Looking for how to get JavaScript array length?

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.

How to get length of array | JavaScript

An array in JavaScript is an object. Thus, we can access properties from it using the dot(.) operator.

One such property is ‘length‘. With the help of this property, you can get the array length.

For example-


// 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.

JavaScript | Create an array of length

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.

Corner cases for array length | JavaScript

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

  • You can use the array length property to get the length of any given array in JavaScript.
  • 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.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.