- The reserved word “new” with an array constructor
- Bracketed syntax called array literal notation
The two syntaxes create an array in exactly the same way. Many developers prefer to use array literal notation because it’s more concise.
let example1 = new Array([“a”, “b”, “c”]); let example2 = [“a”, “b”, “c”];
The reserved word “new” can create an array in two different ways, depending on how you use it with an array constructor. The characteristics of the array depend on whether you give the constructor one numeric parameter or multiple parameters.
let example3 = new Array(1000); // Array with 1000 empty elements let example4 = new Array(1000, 1); // Array with 2 elements
Whitespace between array elements and within an array declaration may span multiple lines if necessary for readability. Whitespace is significant only inside a string. Be careful when the only difference between array indexes is the amount of whitespace, as shown in the second example below — it’s easy to do unintentionally.
let example5 = new Array([ “a”, “b”, “c” ]); let example6 = [ “a” “b”, “c”, “c ” ];
let example7 = [“a”, 1, null, 3, “b”];
let exampleArray = [“my”, “array”, “here”]; console.log(exampleArray); // prints “my” exampleArray = “the”; // changes “my” to “the”
Bracketed notation adds indexes to an array if they don’t already exist. Be careful when adding indexes in this way, though, because you could create empty indexes if you don’t know the length of the array beforehand. If you don’t want empty indexes in the array, empty indexes might cause problems for your code.
let exampleArray = [“my”, “array”, “here”]; exampleArray = “too”; // No gaps exampleArray = “see”; // Skipped index 4, gap
Avoid this problem with the built-in array property
length — it accesses array indexes from the end of the array, rather than the beginning.
exampleArray[exampleArray.length] = “n”; // Adds “n” to end of array exampleArray[exampleArray.length-1]; // Get last array element
Since arrays always access their values via a number inside brackets, avoid numbers at the end of array variable names. You can easily misread an array index if you don’t see where brackets are at first glance, especially since many code editors use monospace fonts. The three examples below, for example, would be easy to mix up with a simple typo.
example8 = “a”; // Set index 15 of array “example8” to “a” example81 = “a”; // Set index 5 of array “example81” to “a” example = “a”; // Set index 815 of array “example” to “a”