Javascript - Array Array Type

Introduction

ECMAScript arrays are ordered lists of data and they can hold any type of data in each slot.

You can create an array that has a string in the first position, a number in the second, an object in the third, and so on.

ECMAScript arrays are dynamically sized and can automatically grow to accommodate any new added data.

Arrays can be created in two basic ways. The first is to use the Array constructor:

var colors = new Array();

You can pass the count into the constructor to set the length property.

var colors = new Array(20);

The Array constructor can also be passed items that should be included in the array.

var colors = new Array("red", "blue", "green");

An array can be created with a single value by passing it into the constructor.

var colors = new Array(3);      //create an array with three items
var names = new Array("red");  //create an array with one item, the string "red"

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

var colors = Array(3);      //create an array with three items
var names = Array("red");  //create an array with one item, the string "red"

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

var colors = ["red", "blue", "green"]; //creates an array with three strings
var names = [];                        //creates an empty array

In this code, the first line creates an array with three string values.

The second line creates an empty array by using empty square brackets.

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

var colors = ["red", "blue", "green"];//define an array of strings
console.log(colors[0]);               //display the first item
colors[2] = "black";                  //change the third item
colors[3] = "brown";                  //add a fourth item

You can append element to an array using index as with colors[3] in this example.

The array length is automatically expanded to be that index plus 1.

Exercise