Arrays

A variable is a reference to a single memory location that has some value. A data structure is a way to store multiple values that have some commonality and can be considered as a collection of values of a similar nature. There are many types of data structures, each serving a particular function or purpose, and the most commonly used one is an Array.

If you consider a variable to be a box in which a value is stored, then an array can be considered a contiguous set of such boxes. The array has one name, and each value stored in an array are accessed using an index value that runs from 0 (which gives the value in the first place in an array) to the length of an array minus one (which gives the value in the last place in an array).

Just as a variable has a data type, an array also specifies the data types of the values it will store. One array can only have values of the same type since the data type is specified at the array level, not for each value. Arrays can be one-dimensional or multi-dimensional (in a two-dimensional array, they can be visualized as a matrix of rows and columns).

One of the advantages of using an array is that you can iterate through an array and retrieve values in sequence or arbitrarily using a dynamically generated index. Arrays solve the problem of declaring one variable for each value, which could get very impractical with a large number of values.

This is how an array is used in a program:

// Declare an array with a variable name and initialize it with some values.
let values_array = [10,20,30,40,50];
// This array now has 5 values, with an index from 0 to 4.
console.log(values_array[0]); // will print 10
console.log(values_array[4]); // will print 50
 
// Arrays come with several functions to allow you to iterate and retrieve each item.
// One such iterator:
values_array.forEach(value => console.log(value)); // Will print all values in the array.