Initialize arrays with literal syntax and the Array constructor.
For the simplest code, using an array literal to start is a good plan. We can have an empty array literal, or one with many elements in it.
Literal example. Here is an integer array with 3 initial elements. The initialization statement is clear and does not require many extra characters. This is ideal.
var values = [10, 20, 30];
console.log("ARRAY: " + values);
Warning: With one argument, we do not get a one-element Array. This specifies a capacity or initial length.
Performance: In a performance test, I found that an initial size can reduce array resizes and lead to better program performance.
// ... Then assign them with indexes.
var values = new Array(3);
values = 10;
values = 20;
values = 30;
console.log("EXAMPLE: " + values);
Constructor, many arguments. With two or more arguments, the Array constructor returns an array with those elements. This is the same as the array literal syntax.
var values = new Array(10, 20, 30);
console.log("VALUES: " + values);
Constructor, no new. The "new" keyword is not required with the Array constructor. Google's Closure Compiler removes the "new" keyword as it is not required and makes the code longer.
// ... It is removed by Closure Compiler.
var result = Array(3);
console.log("RESULT: " + result);
Empty literal. This is a good approach to creating an array. We create an empty array with an empty array literal. Then we push elements to it—we can even do this in a loop.for
Sometimes: We do not know all the elements immediately. This approach allows us to add elements as soon as we know what they are.
var values = ;
console.log("ELEMENTS: " + values);
Unshift. This is the worst approach to building an array. With unshift we add to the front of an array. But this is slow because after each call, all following elements are affected.
var values = ;
console.log("RESULT: " + values);