An array in JavaScript can be defined and initialized in two ways, array literal and Array constructor syntax.
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in square brackets.
let <array-name> = [element0, element1, element2,... elementN];
The following example shows how to define and initialize an array using array literal syntax.
let stringArray = ["one", "two", "three"];
let numericArray = [1, 2, 3, 4];
let decimalArray = [1.1, 1.2, 1.3];
let booleanArray = [true, false, false, true];
let mixedArray = [1, "two", "three", 4];
<aside> 💡 JavaScript arrays can store multiple elements of different data types. It is not required to store values of the same data type in an array.
</aside>
You can initialize an array with the Array constructor syntax using a new keyword.
let arrayName = new Array();
let arrayName = new Array(Number length);
let arrayName = new Array(element1, element2, element3,... elementN);
As you can see in the above syntax, an array can be initialized using new keyword, in the same way as an object.
The following example shows how to define an array using Array constructor syntax.
let stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";
let numericArray = new Array(3);
numericArray[0] = 1;
numericArray[1] = 2;
numericArray[2] = 3;
let mixedArray = new Array(1, "two", 3, "four");
<aside> ⚠️ Please note that arrays can only have numeric index (key). Index cannot be of string or any other data type. The following syntax is incorrect.
</aside>