Declaring Arrays

Intro to Arrays

Declaring Arrays

🙋 Need help? Ask an expert now!

The easiest way to declare an array in JavaScript is to list out its elements. The syntax looks like this:

var variableName = [value1, value2, value3];

Initializing an array can be done separately without declaring each value. There are three ways to initialize an array:

-new Array(elements)
-new Array(initialLength)
-array literal (the method shown above)

The values inside the array can be of any data type, and mixing 2 or more data types into one array will not throw an error. You can also create an array inside an array, which is called a matrix or a 2D array. 2D arrays are pretty complex but are essential when working with objects that are two dimensional (e.g. pixels).

We recommend two methods for declaring and initializing the array. You should either directly list all the values of an array or declare it without putting any values into the array. You can use for loops later in the code to place values inside the elements. The use of the Array object is unnecessary and not recommended when you create arrays. Mixing data types could also be tricky as you don't know which elements hold what value, so sticking to a common data type per array is also something you should consider.

A matrix or a 2D array is something you might want to invest some time into as they will probably crucial in the future when you write more complex programs.

Edit Me on GitHub!

Application Question

Which of the following is a valid array declaration?