Array Length

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

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C"]; //creates an array with three strings 
        var names = [];               //creates an empty array 
        document.writeln(colors.length); //3 
        document.writeln(names.length); //0 
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

length is not read-only.

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

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C"]; //creates an array with three strings 
        colors.length = 2; 
        document.writeln(colors[2]);         //Undefined 
        
        colors[99] = "D";                   //add a color (position 99) 
        document.writeln(colors.length); //100 
        
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The following code adds item to the end of an array.

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C"]; //creates an array with three strings 
        colors.length = 4; 
        document.writeln(colors[3]); //Undefined 
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The following code adds items to the end of an array with the length property:

 
<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">
        var colors = ["A", "B", "C"]; //creates an array with three strings 
        colors[colors.length] = "D"; //add a color (position 3) 
        colors[colors.length] = "E"; //add another color (position 4) 
        document.writeln(colors[0]); 
        document.writeln(colors[1]); 
        document.writeln(colors[2]); 
        document.writeln(colors[3]); 
        document.writeln(colors[4]); 
        document.writeln(colors[5]); 
       
    </script>
</head>
<body>
</body>
</html>
  
Click to view the demo

The last item in an array is always at position length - 1.

Home 
  JavaScript Book 
    Essential Types  

Array:
  1. The Array Type
  2. Array Built-in Methods
  3. Detecting Arrays
  4. Get and set array values
  5. Enumerating the Contents of an Array
  6. Array Length
  7. Array join() method
  8. Array concat()
  9. Array indexOf()
  10. Array lastIndexOf()
  11. Array every()
  12. Array filter() filters array with the given function.
  13. Array map()
  14. Array forEach()
  15. push() and pop():Array Stack Methods
  16. push(), shift():Array Queue Methods
  17. Array reduce()
  18. Array reduceRight()
  19. reverse():Reordering array
  20. Array slice()
  21. Array some()
  22. Array splice()
  23. Array sort()
  24. toString(), toLocaleString() and valueOf Array
  25. Array unshift()