Javascript Reference - JavaScript Array length Property








The number of items in an array is stored in the length property.

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

Browser Support

length Yes Yes Yes Yes Yes

Syntax

To get the length of an array.

var len = array.length;

To set the length of an array:

array.length = newLength;

Return Value

Returns the number of elements in the array object.

Example

The following code shows how to access the length of an array.


//creates an array with three strings
var colors = [ "A", "B", "C" ];
//creates an empty array
var names = [];
console.log(colors.length); //3
console.log("<br/>");
console.log(names.length); //0

The code above generates the following result.





length is not read-only

By setting the length property, you can remove or add items to the end of the array.


//creates an array with three strings 
var colors = ["A", "B", "C"]; 
colors.length = 2; 
console.log(colors[2]);  //Undefined 

//add a color (position 99) 
colors[99] = "D";
console.log(colors.length); //100 

The code above generates the following result.