Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

6. Arrays > Creating Arrays

Creating Arrays

The easiest way to create an array is with an array literal, which is simply a comma-separated list of array elements within square brackets:

var empty = [];             // An array with no elements
var primes = [2, 3, 5, 7];  // An array of 5 numbers
var misc = [{}, true, "a"]; // Elements of various types

The values in an array literal need not be constants; they may be arbitrary expressions:

var base = 1024;
var table = [base, base+1, base+2, base+3];

Array literals can contain object literals or other array literals:

var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]];

If an array literal contains two commas in a row, with no value between, then an element is missing and the array is sparse. Missing elements are undefined:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint