JavaScript array length property explained with 4 examples

The array length property in JavaScript

The array length property of JavaScript is used to set or return total length or number of elements in the specified array.

The JS length property is particularly useful to manipulate array elements.

Generally, this property is used in the for and while loops to get the total number of elements in order to specify the condition part.

 

For example:

It will return 5.

See the following online examples of using the length JavaScript property.

An example of array length property to get total elements

In this example, I have created an array of five elements. After that, the array length property is used to return the number of elements in that array which is assigned to a variable. Finally, the length of array is displayed in an alert.

See online demo and code

An example to use array length property with for loop

In this example, the array length property is used in a for loop for specifying the number of times loop should run i.e. in the condition part. The array elements are displayed in a div element of HTML.

JavaScript length property

See online demo and code

This is how the length property is used in the for loop:

 

The code Arrnum.length specified the condition part of the for loop. In that case, as array elements are five, so loop ran five times.

A length array property example with push method

The length method returns total elements of an array not just at the time of creation but elements added at the later part or dynamically as well.

In this example, an array is created initially with three elements. After that, the push method of arrays is used to add more elements in that array.

The length of array initially and after adding elements are displayed in an alert, as demo page loads.

JavaScript length

See online demo and code

You can see the difference in length before and after using the array push method.

An example of shortening/setting the array length

As such, the length property can be used for setting the array length as well as returning the total number of elements in the array.

In this example, an array is created with five elements. After that, the length property is used to set the array as three. See the code and output online:

JavaScript length set

See online demo and code

This is how the length property is used in the example:

 

You can see, the length of the array is shortened to three elements.