JS: Create Array

By Xah Lee. Date: . Last updated: .

There are 2 ways to create a array:

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 OK

One single comma at the end is ignored.

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

Repeated Comma = Sparse Array

Repeated comma creates a sparse array. (that is, element of that index does not exist) [see JS: Sparse Array]

// repeated comma creates a sparse array.
const x = [9, ,4];

console.log ( x );
// [ 9, <1 empty item>, 4 ]

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


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

Creating Array by Constructor

new Array(…)

JS: Array Constructor

Range Function for Creating Array

JS: Range Function for Array

JS Array

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

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials