JavaScript: The Definitive Guide

Previous Chapter 21
JavaScript Reference
Next
 

Array.length Property

Name

Array.length Property---the size of an array

Availability

Navigator 3.0, Internet Explorer 3.0

Synopsis

array.length

Description

The length property of an array is always one larger than the highest element defined in the array. For traditional "dense" arrays that have contiguous elements and begin with element 0, the length property specifies the number of elements in the array.

The length property of an array is initialized when the array is created with the Array() constructor method. Adding new elements to an array updates the length, if necessary:

a = new Array();    a.length initialized to 0
b = new Array(10);  b.length initialized to 10
c = new Array("one", "two", "three");   c.length initialized to 3
c[3] = "four";  c.length updated to 4
c[10] = "blastoff"; c.length becomes 11

Note that all JavaScript objects can be used as arrays, but only those created with the Array() constructor have an automatically created and updated length property.

You can set the value of the length property to change the size of an array. If you set length to be smaller than its previous value, then the array will be truncated, and elements at the end will be lost. If you set length to be larger than its previous value, then then the array will become bigger, and the new elements added at the end of the array will have the special JavaScript undefined value.

Usage

The Array() constructor and length field were added to JavaScript in Navigator 3.0. Some Navigator 2.0 programs attempt to simulate a length field by setting it in the array constructor methods they write. Note, however, that the length field is not automatically updated as elements are added to the array. Nor can it grow or shrink the array when its value is set.

See Also

"Array", Chapter 8, Arrays


Previous Home Next
Array.join() Book Index Array.reverse()

HTML: The Definitive Guide CGI Programming JavaScript: The Definitive Guide Programming Perl WebMaster in a Nutshell
Hosted by uCoz