JavaScript: 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 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"

Range Function for Creating Array

Range Function for Array

JavaScript Array

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc