JavaScript Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 2.00

Truncating and Iterating Array Elements

This section provides a tutorial example on how to use the array length to truncate and iterate over array elements.

As an object, an array has a special property called "length". You can use the object dot (.) operator to retrieve the length value: "array_name.length".

The array length property can be used to truncate an array by setting the "length" property to a lower value.

The array length property is also useful when you want to iterate all elements of an array.

For example, iterating all elements of an array with a "for" loop can be done as:

for (var i = 0; i < array_name.length; i++) {
  ... array_name[i];
}

Here is a tutorial example JavaScript that shows you how to truncate and iterate array elements with the "length" property:

<html>
<!-- Loop_Array_Elements.html
   Copyright (c) 2008 by Dr. Herong Yang, http://www.herongyang.com/
-->
<head><title>Loop Array Elements</title></head>
<body>
<pre>
<script type="text/javascript">

   // Creating an empty array
   var even_numbers = new Array();

   // Storing 20 elements in the array
   for (var i=0; i<20; i++) {
      even_numbers[i] = i*2;
   }

   // Truncating the array length to 10
   even_numbers.length = 10;
   
   // Iterating all 10 elements
   document.write("First 10 even numbers: ");
   for (var i=0; i<even_numbers.length; i++) {
      document.write(even_numbers[i]+", ");
   }
</script>
</pre>
</body>
</html>

The output of this sample JavaScript is:

First 10 even numbers: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 

Sections in This Chapter

What Is an Array?

Creating an Array Object

Accessing Array Elements with Indexes

Truncating and Iterating Array Elements

Array Object Instance Methods

Array Object Instance Method Examples

Dr. Herong Yang, updated in 2008
Truncating and Iterating Array Elements