How to create array in Javascript

Description

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

Arrays in Javascript are dynamically sized, automatically growing.

Arrays can be created in two ways.

  • Array constructor
  • Array literal notation

Array constructor

The following code uses the Array constructor.

var colors = new Array();

You can pass the count into the constructor, and the length property will set to that value.

var colors = new Array(20);

You can pass items to Array constructor.

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

It's OK 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"


Array literal

An array literal includes square brackets and a comma-separated list of items.


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

Loop

You can enumerate the content of an array using a for loop.


var myArray = [ 100, "A", true ];
for ( var i = 0; i < myArray.length; i++) {
  console.log("Index " + i + ": " + myArray[i]);
}

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions