Why never use new Array in Javascript (Example)

3 min read Original article ↗

I love javascript, but sometimes it seems it doesn't love me back. Take for instance the Array constructor function.

var a = new Array(1,2,3,4,5);
a[0] // returns 1
a.length // returns 5

Wanna take a shot in what this returns?

var a = new Array(10);
a[0] // returns undefined
a.length // returns 10, because of reasons.

This only happens when you give only one integer to the Array constructor. Why, what it's doing? Well, the new Array constructor is taking a page from some programming languages where you needed to specify the memory for your array so you don't get those ArrayIndexOutOfBounds Exceptions.

int *a = (int *) malloc( 10*sizeof(int) ); // ya ol' c
int *a = new int[10]; // c++
int[] a = new int[10]; // java

Yep, it's actually creating an array of with length of 10. We don't have a sizeof function in Javascript, but a toString is enough to prove it.

a.toString() // returns ",,,,,,,,,", a comma for each element + 1

You may think that it is correct "semantics", and it is. How else would you create an array of X length? The catch here is, that I've never needed to define a size in an array, since Javascript doesn't need to allocate memory for an array. They are more like... ArrayLists, if you want to go all Computer Science on it. For instance, all the following code is valid in Javascript:

a.pop(); // returns last object of array, removes it
a.push(20); // puts 20 as the last element of the array, returns length
a.shift();  // returns first object of the array, removes it
a.unshift(30); // puts 30 as the first element of the array, returns length

Using new Array[int] doesn't really have any sense, use, and can prompt to confusion in Javascript. Why? Because native methods of javascript think you know this. For instance, imagine this.

var a = new Array(10);
a.push(30); // returns 11, which if it were a proper stack/queue it would return 10
a.toString() // returns ",,,,,,,,,,20", probably not what you want

We should always use the [] constructor to avoid this kind of things.

var a = [10]
a.toString() // returns "10"
a[0] // returns 10
a.length // returns 1

Am I thinking interview question here? Ask a java/c programmer to create an array of X size and then push elements to it. Just don't be a jerk and ask questions like "What does {} + [] returns?". That's just mean.