JavaScript

How to find the length of an array in JavaScript

A data type called an array is used for storing multiple items of the same type of data, including integers, strings, objects, etc. JavaScript provides a list of array handling support such as length property is used to get or set the length of an array. Although the .length property has manifold uses. However, this article focuses on practicing the length property to find the length of an array.

How to find the length of an array in JavaScript

The JavaScript’s array.length property is the key stakeholder in dealing with the length of an array. The length property of an array element contains the following properties:

  • must be greater than the highest index
  • it is an unsigned 32 bit integer

Syntax

To find the length of an array, the array.length property is exercised which depends on the following syntax.

array.length

The array refers to the array variable which is being examined for finding the length.

Example 1: Using contiguous elements

The following code returns the length of an array that has consistent indexing and the index refers to some value as well.

var staff= ["Mike", "Steve", "Joe", "Alex"];
console.log("The length is: " + staff.length)

The above code creates an array variable and stores various strings inside it. The staff.length used in the second line would print the length of staff array.

Output

The output shows that the length of the array is 1unit ahead of the highest index(3) of the staff array.

Example 2: Non-contiguous

The following code refers to finding the length of an array that has some noncontiguous elements. The noncontiguous concept states that the elements are not in a sequential indexing manner.

var num= [21, , 23, , 25, 28, 31, 34, 37, ,];
console.log("The length is: " + num.length)

In the above code, a num array is created that contains various numbers. However, it is observed that few spaces are left blank. After that the length property of an array is applied on the array to get the length of this array.

Output

The output shows that the array.length has considered the empty elements in the counting.

Conclusion

The length of the array can be obtained by using the length property in JavaScript. In this post, we have demonstrated the ways to get the length of an array element in JavaScript. To do so, the syntax of .length property is explained followed by various examples to better convey the usage of .length property.

About the author

Adnan Shabbir