5.2 Declaring and Initializing Arrays
An array in JavaScript can be defined and initialized in two ways, array literal and Array constructor syntax.
Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in square brackets.
Syntax
let <array-name> = [element0, element1, element2,... elementN];
Example
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];
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.
Array Constructor
You can initialize an array with the Array constructor syntax using a new keyword.
Syntax
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. Example
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");
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.
// INCORRECT !!! let stringArray = new Array(); stringArray["one"] = "one"; stringArray["two"] = "two"; stringArray["three"] = "three"; stringArray["four"] = "four"/hea
Previous Section
5.1 What Are Arrays?Next Section
5.3 Iterating Through ArraysCopyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.