Array Type

In this chapter you will learn:

  1. What is the array type
  2. Array methods we can use
  3. How to get and set array values

The Array Type

JavaScript arrays are ordered lists of data. It can hold any type of data in each slot. JavaScript arrays are dynamically sized.

Arrays can be created by using the array constructor:

<!DOCTYPE html><!--  j  a v a 2  s. c  o m-->
<html>
<head>
    <script type="text/javascript">
        var names = new Array(); 
        document.writeln(names.length);//0
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

Array methods

The JavaScript Array object defines a number of methods you can use to work with arrays.

MethodDescriptionReturns
concat(otherArray)Concatenates the array with the specified array. Multiple arrays can be specified.Array
join(separator)Joins all of the elements in the array to form a string. The argument specifies the character used to delimit the items.string
pop()Treats an array like a stack, and removes and returns the last item in the array.object
push(item)Treats an array like a stack, and appends the specified item to the array.void
reverse()Reverses the order of the items in the array in place.Array
shift()Like pop, but operates on the first element in the array.object
slice(start,end)Returns a sub-array.Array
sort()Sorts the items in the array in place.Array
unshift(item)Like push, but inserts the new element at the start of the array.void

Get and set array values

To get and set array values, you use square brackets and provide the zero-based numeric index:

<!DOCTYPE html><!-- ja  v  a2 s. co  m-->
<html>
<head>
    <script type="text/javascript">
        var colors = ["A", "B", "C"]; //define an array of strings 
        document.writeln(colors[0]); //A,display the first item 
        colors[2] = "black";       //change the third item 
        document.writeln(colors[2]); //,display the third item 
        colors[3] = "brown"; //add a fourth item 
        document.writeln(colors[3]); //display the fourth item 
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

The following code changes the first element in the array:

var myArray = [ 100, "Adam", true ];
myArray[0] = "Tuesday";
document.writeln("Index 0: " + myArray[0]);

Next chapter...

What you will learn in the next chapter:

  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
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()