Array creation

In this chapter you will learn:

  1. How to use array constructor to create array
  2. Create an array with array literal notation
  3. How to create empty array
  4. Put different type values in one array

Array constructor

You can pass the number of item into the constructor, and the length property is set to that value.

var names = new Array(20); 
document.writeln(names.length);//20

The Array constructor can accept array items:

var names = new Array("A", "B", "C"); 
document.writeln(names.length);//3

It's possible to omit the new operator when using the Array constructor.

<!DOCTYPE html><!--from  j  av a 2  s .  com-->
<html>
<head>
    <script type="text/javascript">
        var names = Array("A", "B", "C"); 
        document.writeln(names.length);//3
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Array literal notation

The second way to create an array is by using array literal notation.

The following code creates an array with three strings:

<!DOCTYPE html><!--from   ja v  a  2s  .c o  m-->
<html>
<head>
    <script type="text/javascript">
        var colors = ["red", "blue", "green"]; 
        //creates an array with three strings 
        document.writeln(colors.length);//3
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Empty array

The following code creates an empty array:

<!DOCTYPE html><!--  j av a 2  s. c  om-->
<html>
<head>
    <script type="text/javascript">
        var names = []; //creates an empty array 
        document.writeln(names.length);//0
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Different type values in one array

The following code populates data with different type into an array.

<!DOCTYPE HTML><!--from j a v a 2 s . c o m-->
<html>
<body>
  <script type="text/javascript">
    var myArray = new Array();
    myArray[0] = 100;
    myArray[1] = "Adam";
    myArray[2] = true;
  </script>
</body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. What are the two ways to detect Arrays
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()