Creating Arrays in JavaScript

JavaScript FAQ | JavaScript Arrays FAQ  

Question: How do I create an array in JavaScript?

Answer: You can create an array using either

  • an array initializer (array literal) or
  • the Array constructor.

The array initializer (array literal) syntax is simple: a comma-separated list of values in square brackets. Here are some examples:

var myArray1 = [1,3,5,7,9]      // an array with 5 elements
var myArray2 = [5]              // an array with 1 element
var myArray3 = [true,'Hi',[7]]  // element types need not be the same!
The Array constructor syntax has three different forms. If you call the constructor with two or more arguments, the arguments initialize the array elements. If you only supply one argument to the Array constructor, the argument initializes the length of the new array; the new array’s elements are not initialized. Finally, if you call the constructor without arguments, the new array’s length is set to zero, and its elements are not initialized. Here are examples:
var myArray4 = new Array(1,3,5,7,9)  // an array with 5 elements
var myArray5 = new Array(100)        // an empty array of length 100
var myArray6 = new Array()           // an empty array of length 0

See also:
Creating multidimensional arrays
Deleting an array element
Are arrays a separate data type?

Copyright © 1999-2011, JavaScripter.net.