There are two ways to create an array in JavaScript. You can either create an array literal OR instantiate 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"];
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 no point in doing this for a simple array. This method is worse for performance and longer to write.
However, 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, though:
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 itslength
property set to that number (Note: this implies an array ofarrayLength
empty slots, not slots with actualundefined
values). If the argument is any other number, aRangeError
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 instead.