JavaScript Array length

The length property returns or sets the number of elements in an array.

Example


length Syntax

The syntax to access the length property is:

arr.length

Here, arr is an array.


Example 1: Finding Number of Elements in an Array

Output

4
2
0

Here, we can see that length property returns the number of items in each array. It returns the integer just greater than the highest index in an Array.


Example 2: Using Array length in for loop

Output

JavaScript
Python
C++
Java
Lua

You can also reassign the length property of an Array using the assignment operator =.

Syntax to assign the Array length:

array.length = <Integer>

This can be used to truncate or extend a given array.

Example 3: Changing length property of Array

Output

[ 'JavaScript', 'Python', 'C++' ]
[ 'JavaScript', 'Python', 'C++', <3 empty item> ]

Here, we first truncated the length of Array as 3 (assigned value) is less than 4 (original Array length).

If the assigned value is more than the original Array length, empty items are appended to the end of the Array. We can see this happen in the second example.