Joined May 2011
·

Tim Caswell

The Node Firm
·
Red Lick, Texas, USA
·
·
·

Posted to Why never use new Array in Javascript over 1 year ago

@jjperezaguinaga, I promise you that Array instances are normal objects just like any other object in javascript. Semantically they work just like Object instances except they have a magic .length property and the addition of a bunch of array methods like .forEach(), .map(), .join(), etc.

Arrays are stored by reference just like any other non primitive value. They are mutable. If two variables point to the same array then when the array is changed through one reference, the other reference will see the change since it is the same object.

Regarding using the constructor form with numerical lengths, I find this very useful. There are many cases that I need to quickly create an array of a known size and fill it with data that I get through a loop. For example, to implement Array.prototype.map in ES3 browsers, I would do:

if (typeof Array.prototype.map !== "function") {
  Array.prototype.map = function (callback, thisArg) {
    // Create a new array of the same size
    var length = this.length;
    var arr = new Array(length); 
    for (var i = 0, i < length; i++) {
      arr[i] = callback.call(thisArg, this[i], i, this);
    }
    return arr;
  };
}

It would be silly and slow to create an empty array and grow it using .push(). While it's technically true that setting values outside the array length also cause it to grow, the VMs are able to often optimize the backing store to the array and speed things up when you declare up front how large it is to be.

Posted to Why never use new Array in Javascript over 1 year ago

@jjperezaguinaga are you sure that the Array constructor doesn't return Array instances?

[1,2,3] === [1,2,3] // --> false
Array.isArray([1,2,3]) // --> true
Array.isArray(new Array(1,2,3)) // --> true

Also, while I never use the constructor format to initialize my array values, it's very useful for creating medium sized arrays quickly. Suppose I need to create a 10 length array quickly. It's much faster in most engines to do:

var arr = new Array(100);
for (var i = 0; i < 100; i++) {
  arr[i] = i * i;
}

vs

var arr = [];
for (var i = 0; i < 100; i++) {
  arr.push(i * i);
}

..b.ecause while arrays can resize on the fly, that isn't without cost. It does have to reallocate memory when the size required exceeds the backing store.

Achievements
266 Karma
3,278 Total ProTip Views