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.
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
lengthproperty set to that number (Note: this implies an array of
arrayLengthempty slots, not slots with actual
undefinedvalues). If the argument is any other number, a
RangeErrorexception is thrown.
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.