Add to Array

In this chapter you will learn:

  1. How to add element to the end of an array

Add element to the end of an array

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

<!DOCTYPE html><!--  j a  va  2s.c  o  m-->
<html>
<head>
    <script type="text/javascript">
     //creates an array with three strings 
     var colors = ["A", "B", "C"]; 
     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:

<script type="text/javascript">/*from j av a  2  s. co m*/
    //creates an array with three strings 
    var colors = ["A", "B", "C"];
    //add a color (position 3)  
    colors[colors.length] = "D"; 
    //add another color (position 4) 
    colors[colors.length] = "E"; 
    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>

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

Next chapter...

What you will learn in the next chapter:

  1. How to join array element together
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()