Array Length

In this chapter you will learn:

  1. How to access the number of elements in an array
  2. Array length is not read-only

Array Length

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

<!DOCTYPE html><!--from  j  a  va 2 s . c  om-->
<html>
<head>
    <script type="text/javascript">
        //creates an array with three strings 
        var colors = ["A", "B", "C"];
        //creates an empty array 
        var names = [];               
        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><!--from j  a v  a 2  s . c o m-->
<html>
<head>
    <script type="text/javascript">
        //creates an array with three strings 
        var colors = ["A", "B", "C"]; 
        colors.length = 2; 
        document.writeln(colors[2]);  //Undefined 
        
        //add a color (position 99) 
        colors[99] = "D";
        document.writeln(colors.length); //100 
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to add element to the end of an array
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()