JavaScript: Create Array

By Xah Lee. Date: . Last updated: .

There are 2 ways to create a array:

Creating Array by Literal Expression

// creating array using literal expresion
var x = [3, 4];
console.log(x);        // [ 3, 4 ]
console.log(x.length); // 2

One Single Trailing Comma

One single comma at the end is ignored. (it does not add a undefined element at end, nor does it creates a sparse array. 〔►see JavaScript: Sparse Array〕 )

// one trailing comma is ignored
var x = [3, 4, ];
console.log(x);        // [ 3, 4 ]
console.log(x.length); // 2

// but repeated comma, trailing or not, creates sparse array
var x = [3, 4, ,];
console.log(x);        // [ 3, 4, ]
console.log(x.length); // 3

Repeated Comma

When using literal expression to create array, repeated comma will create sparse array. (that is, element of that index does not exist) 〔►see JavaScript: Sparse Array

// repeated comma creates a sparse array.
var x = ["a", ,"c"];

console.log(x[0]); // a
console.log(x[1]); // prints “undefined”, but element doesn't exist
console.log(x[2]); // c

console.log(x.length); // 3

console.log(Object.getOwnPropertyNames(x)); // [ '0', '2', 'length' ]
// note, there's no property key "1"

Creating Array by Constructor

JavaScript: Array Constructor

How to create a array with a range of elements?

JavaScript: Range Function for Array

Tip: do not use new Array(…). Best to always use literal expression var myArray = […];, and use array method “push”.

〔►see JavaScript: Array.prototype.push

Array Topic

  1. JavaScript: Array Basics
  2. JavaScript: Understand JS Array
  3. JavaScript: Create Array
  4. JavaScript: Sparse Array
  5. JavaScript: Array-Like Object
  6. JavaScript: Array How-To

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.