How to initialize an array’s length in JavaScript?

  1. Why do you want to initialize the length? Theoretically there is no need for this. It can even result in confusing behavior, because all tests that use the length to find out whether an array is empty or not will report that the array is not empty.
    Some tests show that setting the initial length of large arrays can be more efficient if the array is filled afterwards, but the performance gain (if any) seem to differ from browser to browser.
  2. jsLint does not like new Array() because the constructer is ambiguous.new Array(4); creates an empty array of length 4. Butnew Array('4'); creates an array containing the value '4'.

Regarding your comment: In JS you don’t need to initialize the length of the array. It grows dynamically. You can just store the length in some variable, e.g.

var data = [];
var length = 5; // user defined length

for(var i = 0; i < length; i++) {
    data.push(createSomeObject());
}

Leave a Comment