Skip to content
Advertisement

How to initialize an array’s length in JavaScript?

Most of the tutorials that I’ve read on arrays in JavaScript (including w3schools and devguru) suggest that you can initialize an array with a certain length by passing an integer to the Array constructor using the var test = new Array(4); syntax.

After using this syntax liberally in my js files, I ran one of the files through jsLint, and it freaked out:

Error: Problem at line 1 character 22: Expected ‘)’ and instead saw ‘4’.
var test = new Array(4);
Problem at line 1 character 23: Expected ‘;’ and instead saw ‘)’.
var test = new Array(4);
Problem at line 1 character 23: Expected an identifier and instead saw ‘)’.

After reading through jsLint’s explanation of its behavior, it looks like jsLint doesn’t really like the new Array() syntax, and instead prefers [] when declaring arrays.

So I have a couple questions:

First, why? Am I running any risk by using the new Array() syntax instead? Are there browser incompatibilities that I should be aware of?

And second, if I switch to the square bracket syntax, is there any way to declare an array and set its length all on one line, or do I have to do something like this:

var test = [];
test.length = 4;

Advertisement

Answer

  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. But

    new 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());
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement