Arrays

Arrays are a list of elements, and is denoted by two square brackets: []. Within these two square brackets, you can have any number of values, and they can be strings, numbers and booleans.

It is often a good idea to only use one data type in one array, because you often do the same operations on all elements.

[42, 643, 23, 546, 753, 23]
["This is", "an array", "with", "strings"]
[true, false, false, true]

As can be seen, each element in the array is divided by a comma.

An Array can be assigned to a variable or constant, similar to other data types.

var emptyArray = []
emptyArray

>> []

var arrayWithElements = ["just", "another", "element"]
arrayWithElements

>> ["just", "another", "element"]

Arrays has one property and a number of methods available to help us read information and manipulate them, e.g. add or update elements.

The first thing we should know is how to read an element from the Array. So far we have seen how to get the entire array, but that is not practical if we want to do something with the data, e.g. add two numbers. To get the element at index n, we write the name of the array, followed by the wanted index inside square brackets. Indexing starts at zero, meaning that the first element have index 0.

var arrayWithElements = ["just", "another", "element"]
arrayWithElements[1]

>> "another"

If you try to get an element that is not in the array, e.g. the fourth element (index 3), you would get an error.

Arrays have a property called `.length`, which returns the number of elements in the array.

var arrayWithElements = ["just", "another", "element"]
arrayWithElements.length

>> 3

Notice here that the returned value is the number of elements in the array, and that zero-indexing does not affect this. Using the length property, we can get the last element of any array, without knowing the total number of elements. Since arrays are zero-indexed however, we need to subtract one (1) to get the last element.

var arrayWithElements = ["just", "another", "element"]
arrayWithElements[arrayWithElements.length-1]

>> "element"

It is also possible to add elements to the array after its declaration. To do this, we use the method push(). Inside the parentheses we would put whatever value we would like to append to the array. By using this method, the element inside the parentheses will be placed last in the array.

const someArray = []
someArray

>> []

someArray.push("This string")
someArray

>> ["This string"]

In order to remove the last element, we can use the method pop():

const someOtherArray = ["This string", "is my string"]
someOtherArray

>> ["This string", "is my string"]

someOtherArray.pop()

>>  "is my string"

someOtherArray

>> ["This string"]

Notice that when the method pop() is called upon, the last element is returned and removed.

Last updated