JS: Array Constructor

By Xah Lee. Date: . Last updated: .

warning: new Array(9) does not actually create any element in the array at all.

// 「new Array(n)」 does not create any elements, only sets length
const r1 = new Array(2);
console.log(r1.length); // 2
console.log(Object.getOwnPropertyNames(r1)); // [ 'length' ]

// here's array of 2 items, both are undefined
const r2 = [undefined, undefined];
console.log(r2.length); // 2
console.log(Object.getOwnPropertyNames(r2)); // [ '0', '1', 'length' ]

If you create a array by new Array(4), then use the array method map to fill in, it doesn't work.

// creating array by map this way doesn't work

let a1 = new Array(3);
a1 = a1.map( (() => 0));
console.log(a1); // [ <3 empty items> ]
// expected [ 0, 0, 0 ]

Tip: avoid using array constructor. Anything it does can be done better in other ways. Use literal array expression [] then use array method push.

[see JS: Array.prototype.push]

Or use Array.of

[see JS: Array.of]

Range Function for Creating Array

JS: Range Function for Array

Reference

ECMAScript 2015 §Indexed Collections#sec-array-constructor

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