Array literals vs the Array() constructor

There are two ways to create an array in JavaScript. You can either create an array literal OR call the Array() constructor function. Which should you use? Like many things in JavaScript, it depends!

Array literals

To create an array literal, you put a list of values between square brackets:

var fruits = [ "Apples", "Bananas", "Cherries" ];

Like regular expression literals, array literals provide compilation of the array when the script is loaded. Therefore, they can be better for performance.

You’ll use these most of the time.

The Array() constructor

You can also create an array by passing your values into the Array() constructor function:

var fruits = new Array( "Apples", "Bananas", "Cherries" );

There’s really not much point in doing this, though. This method is worse for performance and longer to write.

The nice thing about the Array() constructor is that you can pass in a number. This creates an array with that number of empty slots:

var fruits = new Array( 3 );

console.log( fruits ); // Array(3) [ <3 empty slots> ]

console.log( fruits.length ) // 3

Here’s an important note from the MDN Web Docs:

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values). If the argument is any other number, a RangeError exception is thrown.

Wrapping up

Array literals are better for performance, so you should use these most of the time. If you need to create an array with a number of empty slots, you can use the Array() constructor.


If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!