JS: 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
const 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 JS: Sparse Array] )

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

// but repeated comma, trailing or not, creates sparse array
const y = [3, 4, ,];
console.log(y);        // [ 3, 4, <1 empty item> ]
console.log(y.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 JS: Sparse Array]

// repeated comma creates a sparse array.
const 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

[see JS: Array Constructor]

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

[see JS: Array.prototype.push]

Range Function for Creating Array

JS: Range Function for Array

Array Topic

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

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth